【发布时间】:2015-02-03 00:07:11
【问题描述】:
我只是在学习 fork() 在 C 中的工作原理。 这个想法是产生 3 个子进程,每个子进程都向父进程发送一些信息。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int fd[2];
int pid[3] = {0,0,0};
int status = 0;
for (int i = 0; i < 3; i++)
{
pipe(fd);
pid[i] = fork();
if (pid[i] < 0)
{
return -1;
}
if (pid[i] == 0)
{
close(fd[0]);
char *arr = malloc(sizeof(char));
sprintf(arr, "%i", i);
write(fd[1], arr, 1);
exit(0);
}
}
for(int j=0; j < 3; j++)
{
close(fd[1]);
if (pid[j] > 0)
{
sleep(0);
pid[j] = wait(&status);
char *out = malloc(20 *sizeof(char));
read(fd[0], out, 6);
printf("%s\n", out);
free(out);
printf("I am the parent\n");
}
}
}
预期的输出是:
1
I am the parent
2
I am the parent
3
I am the parent
真正的输出是: 2 我是家长 2 我是家长 2 我是家长
为什么会这样?
【问题讨论】:
-
每次通过您的第一个
for循环时,您调用pipe(fd)并丢失您最后一次围绕循环创建的管道的描述符。三个子进程需要三个管道,这里不是一个。您应该检查 all 系统调用的返回值,而不仅仅是fork()-close(fd[1])如果有的话,会向您大喊大叫。 -
我认为通过在循环内调用 pipe(fd) 可以创建 3 个管道。如果这失败了,那么我该如何制作 3 个管道?
-
@user3614293 创建一个 3x2 数组来保存 3 对文件描述符,就像您对
pids 所做的那样。 -
您正在创建三个管道,但您只保留对最后一个管道的引用。您应该执行
int fd1[2], fd2[2], fd3[2](或int fd[3][2])之类的操作,然后分别对它们中的每一个调用pipe()。 -
谢谢,会试试的。
标签: c pipe multiprocessing