[英]Why parent process reads first from pipe in 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;
}
为您查询:
父进程先读取,然后子进程写入。 我想知道为什么会这样吗?
在fork()之后,两个进程都独立工作,因此将首先调度哪个进程,这取决于调度程序。
如何在此程序中使用两个管道?
打开两个管道,一个管道给父母,另一个管道给孩子。 因为管道是单向的。
int fd[2];
int fd1[2];
parents will write on fd[1] child will read from fd[0]
child will write on fd1[1] parents will read from fd1[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.