0
我已经运行这段代码,发现父进程先读取子进程写入。我想知道为什么会发生这种情况?
此外,我也想知道我怎么可以使用两个管道在此program.i只想概念,任何代码都将appreciated.Thanks为什么父进程首先从管道读取LINUX
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
main()
{
int fd[2];
pid_t childpid;
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
printf("\nChild writes\n\n");
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
printf("parent reads\n\n");
}
return 0;
}
为什么要孩子第一?由于父级在孩子之前开始,所以它很可能首先到达'if(childpid == 0)'。你需要让他等待孩子。 –
如何在程序中使用2个管道和2个孩子 –