2016-02-26 66 views
3

說我分叉N個孩子。我想在1和2,2和3,4和5之間創建管道,等等。所以我需要一些方法來找出哪個孩子是哪個。下面的代碼是我目前擁有的。我只需要一些方法來告訴那個孩子數字n,是孩子數字n。如何區分子進程?

int fd[5][2]; 
int i; 
for(i=0; i<5; i++) 
{ 
    pipe(fd[i]); 
} 
int pid = fork(); 
if(pid == 0) 
{ 
} 
+4

使'pid'成爲大小爲'N'的數組。 – kaylum

+2

哈哈我很笨... –

回答

2

下面的代碼將創建一個管道爲每一個孩子,多次叉的過程,因爲它需要從父發送到每個孩子一個int值(ID,我們想給孩子) ,最後孩子們會讀取價值並終止。

注意:因爲你是分叉的,所以我的變量將包含迭代號,如果迭代號是子id,那麼你不需要使用管道。

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 

int main(int argc, char *argv[]) { 
    int count = 3; 
    int fd[count][2]; 
    int pid[count]; 

    // create pipe descriptors 
    for (int i = 0; i < count; i++) { 
     pipe(fd[i]); 
     // fork() returns 0 for child process, child-pid for parent process. 
     pid[i] = fork(); 
     if (pid[i] != 0) { 
      // parent: writing only, so close read-descriptor. 
      close(fd[i][0]); 

      // send the childID on the write-descriptor. 
      write(fd[i][1], &i, sizeof(i)); 
      printf("Parent(%d) send childID: %d\n", getpid(), i); 

      // close the write descriptor 
      close(fd[i][1]); 
     } else { 
      // child: reading only, so close the write-descriptor 
      close(fd[i][1]); 

      // now read the data (will block) 
      int id; 
      read(fd[i][0], &id, sizeof(id)); 
      // in case the id is just the iterator value, we can use that instead of reading data from the pipe 
      printf("%d Child(%d) received childID: %d\n", i, getpid(), id); 

      // close the read-descriptor 
      close(fd[i][0]); 
      //TODO cleanup fd that are not needed 
      break; 
     } 
    } 
    return 0; 
}