2016-11-23 29 views
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; 
    } 
+0

为什么要孩子第一?由于父级在孩子之前开始,所以它很可能首先到达'if(childpid == 0)'。你需要让他等待孩子。 –

+0

如何在程序中使用2个管道和2个孩子 –

回答

2

为您查询: -

父进程首先读取子进程写入。我想知道为什么会发生这种情况

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]