1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> #include <sys/wait.h>
void waitchild(int signo) { pid_t wpid;
while(1) { wpid = waitpid(-1, NULL, WNOHANG); if(wpid>0) { printf("child is quit, wpid==[%d]\n", wpid); } else if(wpid==0) { printf("child is living, wpid==[%d]\n", wpid); break; } else if(wpid==-1) { printf("no child is living, wpid==[%d]\n", wpid); break; } } }
int main() { int i = 0; int n = 3;
sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigprocmask(SIG_BLOCK, &mask, NULL);
for(i=0; i<n; i++) { pid_t pid = fork(); if(pid<0) { perror("fork error"); return -1; } else if(pid>0) { printf("father: fpid==[%d], cpid==[%d]\n", getpid(), pid); sleep(1); } else if(pid==0) { printf("child: fpid==[%d], cpid==[%d]\n", getppid(), getpid()); break; } }
if(i==3) { printf("[%d]:father: fpid==[%d]\n", i, getpid()); struct sigaction act; act.sa_handler = waitchild; sigemptyset(&act.sa_mask); act.sa_flags = 0; sleep(5); sigaction(SIGCHLD, &act, NULL);
sigprocmask(SIG_UNBLOCK, &mask, NULL);
while(1) { sleep(1); } }
if(i==0) { printf("[%d]:child: cpid==[%d]\n", i, getpid()); }
if(i==1) { printf("[%d]:child: cpid==[%d]\n", i, getpid()); sleep(1); }
if(i==2) { printf("[%d]:child: cpid==[%d]\n", i, getpid()); sleep(1); }
return 0; }
|