1 2 void handler(int sig) 3 { 4 int status; 5 pid_t pid; 6 7 while( (pid = waitpid(-1, &status, 0)) > 0 ) { 8 printf("child %d terminated ", pid); 9 if (WIFEXITED(status)) { 10 printf("with exit value: %d\n", WEXITSTATUS(status)); 11 } else { 12 printf("(did not terminate normally)\n"); 13 } 14 } 15 if ( pid < 0 ) { 16 printf("waitpid error: %s\n", strerror(errno)); 17 } 18 } 19 20 int main() 21 { 22 int i; 23 pid_t pid; 24 25 Signal(SIGCHLD, handler); 26 for(i = 0; i < 5; i++) { 27 if ( (pid = fork()) == 0 ) { 28 sleep(1); 29 printf("child %d exiting\n", getpid()); 30 exit(10+i); 31 } 32 } 33 printf("parent waits in infinite loop: (ctrl-c to end)\n"); 34 35 while(1) { 36 } 37 return 0; 38 }