代碼會是這樣,你應該叉兩個子爲每一個新的子進程,直到達到目標深度水平,分叉兩個子後,父進程必須退出系統,只有新的子進程應該創建新進程,
你可以通過查看childpid(叉的返回值)的代碼
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <math.h>
int main(int argc, char *argv[])
{
pid_t childpid;
int i, n;
if (argc != 2) {
fprintf(stderr, "Usage: %s n\n", argv[0]); return 1;
}
n = atoi(argv[1]);
childpid=-1;
for (i = 1; i <= n; i++){
int b;
for(b=0;b<2;b++)
{
childpid=fork();
if (childpid <= 0) break;
}
if (childpid > 0) break;
}
while(wait(NULL) > 0) ; /* wait for all of your children */
fprintf(stderr, "i:%d process ID:%ld parent ID:%ld child ID:%ld\n",i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
}
輸出丟棄的父進程是這樣的
└──╼ $./fork.o 2
i:3 process ID:23913 parent ID:23911 child ID:0
i:3 process ID:23915 parent ID:23911 child ID:0
i:3 process ID:23914 parent ID:23912 child ID:0
i:3 process ID:23916 parent ID:23912 child ID:0
i:2 process ID:23911 parent ID:23910 child ID:23915
i:2 process ID:23912 parent ID:23910 child ID:23916
i:1 process ID:23910 parent ID:23277 child ID:23912
我只有3行輸出,當我嘗試你的代碼。我還爲'wait()'和固定的'int main()'包含了缺失的庫。 – mch