不要遞歸遞歸。使B成爲A的子進程並不是一個好主意。例如,如果B調用setsid
在自己的會話中運行,它將採用與它無關的A.如果B死了,A會得到一個SIGCHILD,而不是你。尤其是,您將無法獲得B的返回狀態。
下面是在一系列管道上分叉n個子代碼的草圖。警告:我直接在瀏覽器中輸入代碼;可能有很多錯別字,我省略了所有錯誤檢查。
char *executables[n];
char *args[n];
int pipes[2*n+2]; /* child i reads from */
int child_pids[n];
int ret; /*Error checking omitted; abort if ret ever becomes negative*/
ret = pipe(pipes);
for (i = 0; i < n; i++) {
ret = pipe(pipes + 2 * i + 2);
ret = fork();
if (ret == 0) {
/* Code of child i */
close(pipes[2*i+1]);
close(pipes[2*i+2]);
dup2(pipes[2*i], 0);
dup2(pipes[2*i+3], 1);
ret = execv(executables[i], args[i]);
}
close(pipes[2*i]);
close(pipes[2*i+3]);
child_pids[i] = ret;
}
/* interact with the subprocesses, then call wait or waitpid as needed */
後者是什麼貝殼做,大概是一個很好的理由。 – 2012-07-19 20:21:14
@OliCharlesworth:你有參考嗎?或者最好鏈接到示例代碼,所以我不重新發明輪子。 – 2012-07-19 20:22:28
如果你在使用Linux,你可以通過運行'pstree'來推斷它,它顯示所有進程的父子關係。 – 2012-07-19 20:33:44