【问题标题】:Fread blocks eternally on redirected stdout with named pipesFread 在使用命名管道的重定向标准输出上永久阻塞
【发布时间】:2013-06-28 10:12:30
【问题描述】:

我们试图通过在子进程中重定向到标准输入和标准输出的命名管道在两个进程之间进行通信。父进程打开命名管道并对其调用 fdopen。我们看到的问题是 fwrite 在此工作,但是即使永远从重定向的标准输出管道块中读取一个字节。 该代码在使用文件描述符而不是 FILE * 时有效。怎么了?代码有点长,抱歉。

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int create_fifo()
{
    int file1;
    unlink("fifo-0.0");
    file1 = mkfifo("fifo-0.0",0666); 
    if(file1<0) {
        printf("Unable to create a fifo");
        return 0;
    }
    unlink("fifo-0.1");
    file1 = mkfifo("fifo-0.1",0666); 
    if(file1<0) {
        printf("Unable to create a fifo");
        return 0;
    }
    return 1;
}

int main()
{
    int fd, fd0, fd1;
    pid_t pid;
    char read_buf_p[50],write_buf_p[50];
    char * args[3];
    FILE *fd_stdin_p, *fd_stdout_p;

    create_fifo();
    args[0] = "/bin/cat";
    args[1] = "-n";
    args[2] = NULL;

    pid = fork();
    if(pid == 0)
    {   
        fd = open("fifo-0.0", O_RDONLY);
        dup2(fd, 0);
        close(fd);
        fd = open("fifo-0.1", O_WRONLY);
        dup2(fd, 1);
        close(fd);
        execv(args[0],args);
    }
    else
    {
        fd0 = open("fifo-0.0", O_WRONLY);
        fd_stdin_p = fdopen(fd0,"w");
        fd1 = open("fifo-0.1", O_RDONLY);
        fd_stdout_p = fdopen(fd1,"r");
        int sz = fwrite("Hello World", sizeof(char), strlen("Hello World"), fd_stdin_p);
        fread(read_buf_p,1,1,fd_stdout_p);
        printf("%s\n", read_buf_p);
    }
    return 0;
}

【问题讨论】:

    标签: c linux


    【解决方案1】:

    我认为这是因为标准输出的缓冲。 只需在 fflush() 的末尾使用 '\n'

    【讨论】:

      【解决方案2】:

      这是默认情况下基于FILE 的I/O 被“行缓冲”的结果。这意味着它读取和写入整行,并且由于您的数据不是整行,因此它卡在缓冲区中并且没有传递到底层文件描述符。

      尝试在输出数据末尾添加\n,或调用fflush()

      【讨论】:

      • 作为后续:另一种选择是在文件流指针上使用 setbuf() 来禁用缓冲。取决于什么对开发者更有效
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 2017-06-06
      • 2018-05-15
      • 1970-01-01
      相关资源
      最近更新 更多