#include "csapp.h"
#define BUF_SIZE 16
void handler_sigchld(int sig);
int main()
{
int i;
char *buf = (char *)malloc(BUF_SIZE * sizeof(char));
signal(SIGCHLD, handler_sigchld);
for(i = 0; i < 3; i++){
if(Fork() == 0){
printf("Child process %d\n", (int)getpid());
sleep((i + 1) * 5);
exit(0);
}
}
while(read(STDIN_FILENO, buf, BUF_SIZE)){
printf("Parent process running, got the input: %s\n", buf);
memset(buf, '\0', BUF_SIZE);
}
free(buf);
return 0;
}
void handler_sigchld(int sig)
{
int pid, olderrno = errno;
while((pid = waitpid(-1, NULL, 0)) > 0){
printf("Got process %d's SIGCHLD\n", pid);
}
if(errno == ECHILD){
printf("done.\n");
}
errno = olderrno;
}
以上是我小改的例程代码,下面是运行结果:
我的疑问是:那个处理子进程结束信号的函数handler_sigchld被调用了3次,为什么只有2次正常的结束(也就是只输出了2次done.)?