使用管道

时间:2016-04-13 16:04:12

标签: c fork pipeline wc

我正在编写一个在子进程上执行word count命令的程序。父进程应该将用户输入的一系列行通过管道发送到子进程。 我试图这样做,但我最终得到了一个错误。 这是我的代码:

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;
}

我还尝试使用dup2将子项的标准输入与父进程创建的管道的读取描述符相关联。 但是我收到了这个错误:wc: standard input: Input/output error 我该如何解决?

UPDATED (错误已解决,但我获得了无限循环)

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;
}

1 个答案:

答案 0 :(得分: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;
}