如何区分subprocess?

说我叉N个孩子。 我想在1和2,2和3,4和5之间创buildpipe道,等等。 所以我需要一些方法来弄清楚哪个孩子是哪个。 下面的代码是我现在有。 我只是需要一些方法来告诉那个孩子号码n,是孩子号码n。

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

下面的代码将为每个子进程创建一个管道,根据需要多次分配进程,并从父进程向每个子进程发送一个int值(我们要给这个子进程的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; }