0

I have a problem with execlp. When I do not know how to redirect command from arrays of pointers to execlp correctly. For example i want to use

ls -l | sort -n

my program takes only "ls" and "sort"

      int pfds[2];
      pipe(pfds);
      child_pid = fork();
      if(child_pid==0)
      {       
        close(1);
            dup(pfds[1]);   
            close(pfds[0]); 
            execlp(*arg1, NULL);

      }
      else 
      {
        wait(&child_status); 
            close(0);
        dup(pfds[0]);
        close(pfds[1]); 
            execlp(*arg2, NULL);
      }

All commands are in arrays of pointers where: ls -l is in first table and sort -n in second

  • Your bigger problem is that having the parent `wait` on `ls` and then exec `sort` is the wrong way to go about this. – Duck Jan 08 '14 at 17:36
  • Are you suggesting to delete the wait command? – user3174326 Jan 08 '14 at 17:42
  • 2
    No, you should `fork` two children (in this case) to form a pipeline. The reason this works now is that you probably been listing small dirs. If you ls a larger one your 'ls' will write to the pipe until it fills PIPE_BUF bytes and then it is going to block on the write (because nothing is reading it) and never end. You will `wait` forever for something that is not going to end (on its own). – Duck Jan 08 '14 at 17:46
  • Study the source code of a small free software shell like `sash` (or a larger one like `bash`) – Basile Starynkevitch Jan 08 '14 at 17:56

1 Answers1

0

You probably wanted to use dup2 to redirect stdin and stdout. Also you are not using execlp correctly. It expects variable number of parameters terminated by NULL pointer. And as suggested by comments, the wait command shall not be there.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    int pfds[2];
    pipe(pfds);
    int child_pid;
    child_pid = fork();
    if(child_pid==0)
    {       
        dup2(pfds[1], 1);   
        close(pfds[0]); 
        execlp("ls", "-al", NULL);

    }
    else 
    {
        dup2(pfds[0], 0);
        close(pfds[1]); 
        execlp("sort", "-n", NULL);
    }
}
Marian
  • 7,402
  • 2
  • 22
  • 34
  • But I do not know what my command 'ls -l | sort -n' is example. Command is given by user. It can be 'ls -l | sort' – user3174326 Jan 08 '14 at 17:47