1 #include <stdlib.h> 2 #include <stdio.h> 3 #include <errno.h> 4 #include <unistd.h> 5 #include <sys/wait.h> 6 void fork_chain(int level) 7 { 8 int pid; 9 10 printf ("forking level %d\n", level); 11 fflush (stdout); 12 pid = fork(); 13 if (pid == -1) { 14 perror("fork"); 15 exit(1); 16 } 17 18 if (pid == 0) { 19 if (level > 0) { 20 fork_chain (level - 1); 21 } 22 } else { 23 int ret; 24 int status; 25 while((ret = waitpid(pid, &status, 0)) != pid) { 26 if (errno != EINTR) { 27 perror("waitpid"); 28 exit(1); 29 } 30 } 31 } 32 } 33 int main() 34 { 35 fork_chain (15); 36 return 0; 37 } 38