C 管道 : Parent to read from child before child ends

标签 c fork pipe

下面的代码显示了子进程如何写入管道端,然后父进程如何从另一端读取 . 在试验代码后我注意到,只有在子进程终止 之后,父进程才能读取 数据。

有没有办法强制父进程在子进程调用write()后立即到前台读取数据?有没有办法在不终止 child 的情况下读取数据?

#include <stdio.h> /* For printf */
#include <string.h> /* For strlen */
#include <stdlib.h> /* For exit */

#define READ 0 /* Read end of pipe */
#define WRITE 1 /* Write end of pipe */
char *phrase = "This is a test phrase.";
main(){
    int pid, fd[2], bytes;
    char message[100];

    if (pipe(fd) == -1) { /* Create a pipe */
        perror("pipe"); 
        exit(1); 
    }
    if ((pid = fork()) == -1) { /* Fork a child */
        perror("fork"); 
        exit(1); 
    }
    if (pid == 0) { /* Child, writer */
        close(fd[READ]); /* Close unused end */
        write(fd[WRITE], phrase, strlen(phrase)+1);
        close(fd[WRITE]); /* Close used end */
    } 
    else { /* Parent, reader */
        close(fd[WRITE]); /* Close unused end */
        bytes = read(fd[READ], message, sizeof(message));
        printf("Read %d bytes: %s\n", bytes, message);
        close(fd[READ]);  /* Close used end */
    }
}

最佳答案

你错了。尝试在“子”部分关闭管道的写入端之前添加 sleep(120) 调用并运行您的应用程序。

关于C 管道 : Parent to read from child before child ends,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12649170/

相关文章:

c - 在 C 中使用 qsort

使用多个 fork() 子项计算表达式?

fork - 为什么我的防病毒程序没有检测到这种恶意行为?

fork后创建管道

c++ - 作为日志旋转器通过管道传输到我的程序

c - 尝试使用 fread 读取字节但出现 Segmentation Fault 11

c - 为什么 malloc 不能与 strcpy 一起使用?

c - 在 Linux 上 undefined reference 但在 Mac 上工作正常

c - 为什么我的信号处理程序执行两次?

c++ - stdin/stdout/stderr 上的跨平台 (linux/Win32) 非阻塞 C++ IO