c - pipe 和 fork : Sharing one file descriptor across multiple children

标签 c posix

<分区>

我有一个多次 fork 的父进程。我在程序开始时管道一次,然后 fork 多次。我可以在所有子项中使用相同的文件描述符来写入父项吗?或者我是否必须为每个新 child 进行管道传输并为每个 child 都有一个单独的文件描述符?

截至目前,第一个 child 可以毫无问题地写入管道的写入端,但第二个 child 在尝试写入时遇到错误的文件描述符错误。

要编写的代码对所有 child 都是一样的。

最佳答案

but the second child gets a bad file descriptor error when it tries to write.

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

#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);
    }   
}

关于c - pipe 和 fork : Sharing one file descriptor across multiple children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26084823/

相关文章:

linux - 来自 kleinanzeigen.ebay.de 的 wget 文章和图片返回 'ERROR 429: Too many requests'

c - 进程中的特定线程是否可以创建多个作业?

c - 段错误(核心已转储)- 错误在哪里?

c - 分配多维数组和不兼容的类型

c - 如何杀死fork的 child ?

c++ - Visual Studios 能否用于在 C++ 中进行开发并仍然创建能够在 Mac 上运行的程序?

c - 是否可以在C中覆盖SSH期望从/dev/tty输入密码

regex - 使用 regexp_split_to_array 将文本列拆分为 2

c++ - sem_destroy 一个信号量被其他人持有 sem_wait?

c++ - putchar_unlocked 在 C++ 14 标准中不起作用