因为当已经进入信号处理函数里,说明在子进程里已经执行了_exit(0),在信号处理函数里注册信号SIGCLD的处理函数时,虽然会检测是否有需要的子进程,可是结果没有,因为已经执行_exit(0);所以不会死循环。书中错。
一、源代码:
cat -n 10_6.c
1 #include "apue.h"
2 #include <sys/wait.h>
3
4 static void sig_cld(int);
5
6 int main()
7 {
8 pid_t pid;
9 if ((pid = fork()) <0 ){
10 err_sys("fork error");
11 }
12 if (signal(SIGCHLD,sig_cld) == SIG_ERR){
13 err_sys("signal SIGCLD handler establish error");
14 }
15
16 //if ((pid = fork()) <0 ){
17 // err_sys("fork error");
18 //}
19 if (pid == 0){
20 sleep(2);
21 _exit(0);
22 }
23
24 pause();
25 exit(0);
26 }
27
28 static void sig_cld (int signalno)
29 {
30 pid_t pid;
31 int status;
32 printf("signal SIGCHLD received.\n");
33 if (signal(SIGCHLD,sig_cld) == SIG_ERR){
34 err_sys("signla SIGCLD handler establish error.");
35 }
36
37 if ((pid = wait(&status)) < 0){
38 err_sys("wait child error.");
39 }
40
41 printf("pid = %d\n",pid);
42
43 }
二、编译及执行结果
:gcc -Wall -gdb3 -o handler_sigcld 10_6.c
cc1: warning: `-gdb3' not supported by this configuration of GCC
In file included from apue.h:132,
from 10_6.c:1:
error.c: In function `err_doit':
error.c:121: warning: implicit declaration of function `vsnprintf'
error.c:123: warning: implicit declaration of function `snprintf'
10_6.c: In function `sig_cld':
10_6.c:41: warning: int format, pid_t arg (arg 2)
./handler_sigcld
signal SIGCHLD received.
pid = 24916