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