简体   繁体   中英

Executing wc command on child process using pipeline

I'm writing a program that executes the word count command on the child process. The father process should send a sequence of lines entered by the user trough a pipeline to the child process. I tried to do this but I ended up with an error. This is my code:

int main ()
{
    int fd[2];
    char buff;
    int pid;
    int pip;
    pid = fork();
    pip = pipe(fd);

    if (pid != 0)
    {
        pip = pipe(fd);
        if (pipe == 0)
        {
            while (read(fd[0], &buff,1) > 0 )
            {
                write (fd[1],&buff,1);      
            }
            close(fd[0]);
            _exit(0);
        }
    }
    else
    {
        dup2(fd[1],1);
        close(fd[1]);
        execlp ("wc","wc",NULL);
        _exit(-1);
    }
    return 0;
}

I've also tried to use dup2 to associate the standard input from the child to the read descriptor of the pipe created by the father process. But I get this error : wc: standard input: Input/output error . How can I solve this?

UPDATED (the error is solved but I get an infinite loop)

int main ()
{
    int fd[2];
    char buff;
    int pid;
    int pip;

    pip = pipe(fd);

    if (pip == 0)
    {
             pid = fork();
         if (pid != 0)
          {     

            while (read(fd[0], &buff,1) > 0 )
            {
                write (fd[1],&buff,1);      
            }
            close(fd[0]);

          }
          else {

        dup2(fd[1],1);
        close(fd[1]);
        execlp ("wc","wc",NULL);
        _exit(-1);
          }
    }
    return 0;
}
#include <unistd.h>

int main ()
{
    int fd[2];
    char buff;
    int pid;
    int pip;
    int status;

    pip = pipe(fd);

    if (pip == 0)
    {
        pid = fork();
        if (pid != 0)
        {
            close(fd[0]);
            while (read(0, &buff,1) > 0 )
            {
                write (fd[1],&buff,1); /* your old loop forwarded internally in the pipe only*/
            }
            close(fd[1]);
         } else {
             dup2(fd[0],0);  /* you had dup2(fd[1], 1), replacing stdout of wc with the write end from wc */
             close(fd[0]);
             close(fd[1]);
             execlp ("wc","wc",NULL);
             _exit(-1);
          }
    }
    wait(&status); /* reap the child process */
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM