Тексты программ
waitid2.c

  1 #include <sys/types.h>
  2 #include <unistd.h>
  3 #include <wait.h>
  4 #include <stdlib.h>
  5 #include <stdio.h>
  6 #include <signal.h>
  7 #define MAXTRIES 8
  8
  9 main()
 10 {
 11     static siginfo_t stat;
 12     pid_t child1;
 13     int try = 0;
 14
 15     if ((child1 = fork()) == 0) {
 16         execl("sleeper", "sleeper", (char *) 0);
 17         exit(1);
 18     }
 19     printf("parent: waiting for child %ld\n", child1);
 20     while (waitid(P_PID, child1, &stat,
 21         WNOHANG|WEXITED) != -1) {
 22         if (stat.si_pid == 0) {
 23             if (try < MAXTRIES) {
 24                 try++;
 25                 sleep(1);
 26                 continue;
 27             }
 28             else {
 29                 printf("sending signal to child\n");
 30                 kill(child1, SIGKILL);
 31                 continue;
 32             }
 33         }
 34         printf("tries = %d\n", try);
 35         printf("child signal no: %d\n", stat.si_signo);
 36         printf("child signal code: %d\n", stat.si_code);
 37         if (stat.si_code == CLD_EXITED)
 38             printf("exit status is: %d\n", stat.si_status);
 39         else
 40             printf("child signal is: %d\n", stat.si_status);
 41     }
 42     printf("parent: child completed\n");
 43 }
waitpid.c

  1 #include <sys/types.h>
  2 #include <unistd.h>
  3 #include <stdlib.h>
  4 #include <wait.h>
  5 #include <stdio.h>
  6 #include <signal.h>
  7 #define MAXTRIES 7
  8
  9 main()
 10 {
 11     pid_t child1, pid;
 12     int status, try = 0;
 13
 14     if ((child1 = fork()) == 0) {
 15         execl("sleeper", "sleeper", (char *) 0);
 16         exit(1);
 17     }
 18     printf("parent: waiting for child\n");
 19     while ((pid = waitpid(child1, &status, WNOHANG))
 20             != -1) {
 21         if (pid == 0) {
 22             if (try < MAXTRIES) {
 23                 try++;
 24                 sleep(1);
 25                 continue;
 26             }
 27             else {
 28                 printf("sending signal to child\n");
 29                 kill(child1, SIGKILL);
 30                 sleep(1);
 31                 continue;
 32             }
 33         }
 34         if (WIFEXITED(status))
 35             printf("child status %d\n",
 36                 WEXITSTATUS(status));
 37         else
 38             printf("child signal %d\n",
 39                 WTERMSIG(status));
 40         printf("tries = %d\n", try);
 41     }
 42     printf("parent: all children terminated\n");
 43 }