<分区>
我有一个多次 fork 的父进程。我在程序开始时管道一次,然后 fork 多次。我可以在所有子项中使用相同的文件描述符来写入父项吗?或者我是否必须为每个新 child 进行管道传输并为每个 child 都有一个单独的文件描述符?
截至目前,第一个 child 可以毫无问题地写入管道的写入端,但第二个 child 在尝试写入时遇到错误的文件描述符错误。
要编写的代码对所有 child 都是一样的。
<分区>
我有一个多次 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/