无法使用管道打印字符串

标签 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);
    }

}

最佳答案

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)

关于无法使用管道打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16968547/

相关文章:

c - 分配共享内存时出错

c - 使用 OpenCV C API 对 CvArr 中所有元素求和

c - C 中的 Bit Hack 看不懂

读取管道后 bash 返回代码

bash - 为什么 tee 无法写入标准输出?

linux - 将 tar.gz 文件中包含的文件通过管道传输到 bash 中的 C++ 程序

objective-c - 混淆 LLDB 输出

c++ - 将代码从 C++ 转换为 C : `a+b > b+a` where a and b are `string`

c++ - 如何有效地使用 boost::process::async_pipe 进行写入和读取?

c - 执行 execve() 的正确步骤是什么?