管道和分支:跨多个子项共享一个文件描述符

时间:2014-09-28 12:24:00

标签: c posix

我有一个多次分叉的父进程。我在程序开始时管道一次,然后多次fork。我可以在所有子节点上使用相同的文件描述符来写入父节点吗?或者我是否必须为每个新孩子进行管道处理并为每个孩子设置单独的文件描述符?

截至目前,第一个孩子可以写入管道的写入端没有问题,但第二个孩子在尝试写入时会收到错误的文件描述符错误。

要编写的代码在所有孩子中都是一样的。

2 个答案:

答案 0 :(得分:1)

  

但第二个孩子在尝试写入时会收到错误的文件描述符错误。

当然,因为对于每个新进程,您需要打开要处理的新文件才有效。 只需为每个新流程打开管道

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

#include <sys/stat.h>
#include <sys/types.h>

#include <fcntl.h> 
char str1[] = "string from 1-st proc";
char str2[] = "string from 2-st proc";
int main(int argc, char *argv[])
{
    char buf[100];
    mkfifo("/tmp/my_fifo", 0777);
    if (fork() == 0) {
        //it is child
        int pipe_chld = open("/tmp/my_fifo", O_WRONLY);
        write(pipe_chld, str1, sizeof(str1));
        if (fork() == 0) {
            //it is child
            int pipe_chld = open("/tmp/my_fifo", O_WRONLY);
            write(pipe_chld, str2, sizeof(str2));
            exit(0);
        } else {
            exit(0);
        }
    } else {
        //it is parent
        int fd_fifo = open("/tmp/my_fifo", O_RDONLY);
        read(fd_fifo, buf, 100);
        read(fd_fifo, buf + sizeof(str1), 100);
        printf("%s, %s\n", buf, buf + sizeof(str1));
        exit(0);
    }   
}

答案 1 :(得分:0)

所以我是个白痴。当我进入程序时,我分叉了一次,在父级中关闭了管道的写入端,然后再次分叉,为后续的子项提供了一个封闭的写入结束。

pipe(fd);
pid = fork();

if (!pid) { /* Insert first child code */ }
else {

    close(fd[1]);    /* Close write end of pipe */

    pid = fork();    /* Fork again. */
    /* ... */

}