[英]waitpid and signal handler, C
I tried to find an answer to my question at this post: Signal handler and waitpid coexisting but for me isn't very clear at the moment. 我试着在这篇文章中找到我的问题的答案: 信号处理程序和waitpid共存,但对我来说目前还不是很清楚。
I try to explain my problems: 我试着解释我的问题:
I'm trying to write a C program that concerns IPC between a parent process and its children. 我正在尝试编写一个关于父进程与其子进程之间的IPC的C程序。 The parent process creates N child processes, then it waits for the termination in a loop like this:
父进程创建N个子进程,然后等待循环终止,如下所示:
while((pid_term = waitpid(-1, &status, 0)) != -1)
After X seconds, parent receives SIGALRM, then with the sigaction system call, it catches the alarm: 在X秒之后,父接收SIGALRM,然后通过sigaction系统调用,它捕获警报:
struct sigaction act;
act.sa_handler = alarmHandler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGALRM, &act, NULL);
But, when the handler function returns, the waitpid also returns -1, and the parent process exits from the while loop above. 但是,当处理程序函数返回时,waitpid也返回-1,父进程从上面的while循环退出。 At the moment, the handler function has an empty body.
目前,处理函数有一个空体。
I ask myself what happened — why did waitpid()
return -1 after the handler invocation even though most of the children are still alive? 我问自己发生了什么 - 为什么
waitpid()
在处理程序调用之后返回-1,即使大多数孩子还活着? Why doesn't this happen with signal()
function? 为什么不用
signal()
函数发生这种情况?
The default behavior of signal handlers established by sigaction
is to interrupt blocking system calls; 由
sigaction
建立的信号处理程序的默认行为是中断阻塞系统调用; if you check errno
after the alarm fires you should observe it to be set to EINTR
. 如果你在警报发生后检查
errno
,你应该观察它被设置为EINTR
。 This behavior is almost never what you want; 这种行为几乎不是你想要的; it's only the default for backward compatibility's sake.
它只是向后兼容性的默认值。 You can make it not do this by setting the
SA_RESTART
bit in sa_flags
: 您可以通过在
sa_flags
设置SA_RESTART
位来使其不这样做:
struct sigaction act;
act.sa_flags = SA_RESTART;
act.sa_handler = alarmHandler;
sigemptyset(&act.sa_mask);
sigaction(SIGALRM, &act, 0);
One of the most important reasons to use sigaction
instead of signal
, is that when you use signal
it is unpredictable whether or not the signal handler will interrupt blocking system calls. 使用
sigaction
而不是signal
的最重要原因之一是,当你使用signal
时,信号处理程序是否会中断阻塞系统调用是不可预测的 。 (The System V lineage picked one semantic and the BSD lineage picked the other.) (System V谱系选择了一个语义,BSD谱系选择了另一个。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.