在此示例中,取自 CSAPP 书籍第 8 章:\#include \'csapp.h\'/* 警告:此代码有缺陷!\*/void handler1(int sig){int olderrno = errno; if ((waitpid(-1, NULL, 0)) < ...
这是来自 CSAPP 书第 8 章的一个例子:
\#include "csapp.h"
/* WARNING: This code is buggy! \*/
void handler1(int sig)
{
int olderrno = errno;
if ((waitpid(-1, NULL, 0)) < 0)
sio_error("waitpid error");
Sio_puts("Handler reaped child\n");
Sleep(1);
errno = olderrno;
}
int main()
{
int i, n;
char buf[MAXBUF];
if (signal(SIGCHLD, handler1) == SIG_ERR)
unix_error("signal error");
/* Parent creates children */
for (i = 0; i < 3; i++) {
if (Fork() == 0) {
printf("Hello from child %d\n", (int)getpid());
exit(0);
}
}
/* Parent waits for terminal input and then processes it */
if ((n = read(STDIN_FILENO, buf, sizeof(buf))) < 0)
unix_error("read");
printf("Parent processing input\n");
while (1)
;
exit(0);
}
它生成以下输出:
......
Hello from child 14073
Hello from child 14074
Hello from child 14075
Handler reaped child
Handler reaped child //more than one child reaped
......
使用的 if 块 waitpid()
用于生成 waitpid()
无法收获所有子进程的错误。 While I understand that waitpid()
is to be put in a while()
loop to ensure reaping all children, what I don't understand is that why only one waitpid()
call is made, yet was able to reap more than one children(Note in the output more than one child is reaped by handler)? 根据这个答案: 为什么信号处理程序中的 waitpid 需要循环? waitpid()
只能收获一个子进程。
谢谢!
更新: 这无关紧要,但处理程序通过以下方式进行更正(也取自 CSAPP 书):
void handler2(int sig)
{
int olderrno = errno;
while (waitpid(-1, NULL, 0) > 0) {
Sio_puts("Handler reaped child\n");
}
if (errno != ECHILD)
Sio_error("waitpid error");
Sleep(1);
errno = olderrno;
}
在我的 Linux 计算机上运行此代码。