2

I am writing a C program which will run Linux commands, like:
cat /etc/passwd | grep list | cut -c 1-5
and i didnt have any result
*here the parent wait for the first child(child_pid) to finish;
and the first child wait for the second(pfils) !!
any idea?
code :

main()
{
    pid_t child_pid;
    int fd[2];
    int pfd[2];
    pipe(pfd);
    child_pid = fork ();

    if (child_pid != 0) 
    {
        wait(child_pid);
        close(pfd[1]);
        dup2(pfd[0],0);
        close(pfd[0]);
        execlp("cut","cut","-c","1-5",NULL);
    }
    else
    {
        pid_t pfils = fork();
        pipe(fd);

        if(pfils == 0)
        {
            close(fd[0]);
            dup2(fd[1],1);
            close(fd[1]);
            execlp("cat", "cat","/etc/passwd",NULL);
        }
        else
        {
            wait(pfils);
            close(fd[1]);
            dup2(fd[0],0);
            close(fd[0]);
            close(pfd[0]);
            dup2(pfd[1],1);
            close(pfd[1]);
            execlp("grep","grep","list",NULL);
        }
    }
}
Inisheer
  • 20,376
  • 9
  • 50
  • 82
falcon1990
  • 23
  • 6
  • One aspect of a pipeline is concurrency, especially on a modern computer with multiple cores. In general, you can't wait for the first process in pipeline to complete before launching the second because the first process may generate more data than can be stored in a pipe. You end up with the first process waiting for the second to read, while the second is waiting for the first to die before it launches its worker code. You should also have error reporting code after the `execlp()` calls just in case the `execlp()` fails. – Jonathan Leffler Jan 12 '13 at 05:35
  • @falcon1990 You not need to wait() in child process,,,I would like to share a link[**A Good Code for Shell**](http://www.ladweb.net/src/ladsh4.c.html) – Grijesh Chauhan Jan 12 '13 at 05:43

1 Answers1

5
    pid_t pfils = fork();
    pipe(fd);

Fork will make a copy of the process. An independent copy of the process. So, if you call pipe after fork, each copy of the process gets their own pipe. Put pipe() before fork() and it should work.

KrHubert
  • 1,030
  • 7
  • 17