1

我们正在尝试通过重定向到子进程中的标准输入和标准输出的命名管道在两个进程之间进行通信。父进程打开命名管道并对其调用 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;
}
4

2 回答 2

1

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

于 2013-06-28T11:02:18.337 回答
0

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

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

于 2013-06-28T10:18:11.280 回答