我运行了这段代码,发现父进程先读取,然后子进程写入。我想知道为什么会这样?
另外我还想知道如何在这个程序中使用两个管道。我只是想要概念,任何代码都会受到赞赏。谢谢
#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]
关于c - 为什么父进程首先从 LINUX 中的管道读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40757631/