无法使用管道打印字符串

时间:2013-06-06 17:33:51

标签: c pipe

我正在努力让我的第一个管道工作:基本上我已经找到了一个程序,应该在屏幕上显示输入的内容。事情是只有少数字符被打印(通常只有第一个)而且我真的很挣扎得到原因。我的代码是:

if ( pid > 0 ) //If I'm the parent
{
    close(fd[0]);
    //as long as something is typed in and that something isn't 
    // the word "stop"
    while (((n = read(STDIN_FILENO, buffer, BUFFERSIZE)) > 0) && 
           (strncmp(buffer, "stop", 4) != 0))
    {
        //shove all the buffer content into the pipe
        write(fd[1], buffer, n);
    }

}
else //If I am the child
{
    close(fd[1]);

    //as long as there's something to read
    while (pipe_read = read(fd[0], buf, BUFFERSIZE) > 0)
    {
        //display on the screen!
        write(STDOUT_FILENO, buf, pipe_read);
    }

}

1 个答案:

答案 0 :(得分:4)

while (pipe_read = read(fd[0], buf, BUFFERSIZE) > 0)

运营商>的优先级高于=pipe_read将具有表达式的值:

read(fd[0], buf, BUFFERSIZE) > 0

根据比较结果,这是1或0。这就是write只打印一个字符的原因。

while ((pipe_read = read(fd[0], buf, BUFFERSIZE)) > 0)