【发布时间】:2021-04-12 06:30:24
【问题描述】:
为了更好地理解sigsuspend 的概念,我做了如下两处修改,得到了不同的输出信息,让我很困惑。
代码来自
csapp Chapter8 figure 8-42约sigsuspend。
-
添加第 10 行
printf("Reap child %d\n", pid);
/* $begin sigsuspend */
#include "csapp.h"
volatile sig_atomic_t pid;
void sigchld_handler(int s)
{
int olderrno = errno;
pid = Waitpid(-1, NULL, 0);
printf("Reap child %d\n", pid); //Line 10
errno = olderrno;
}
void sigint_handler(int s)
{
}
int main(int argc, char **argv)
{
sigset_t mask, prev;
Signal(SIGCHLD, sigchld_handler);
Signal(SIGINT, sigint_handler);
Sigemptyset(&mask);
Sigaddset(&mask, SIGCHLD);
while (1) {
Sigprocmask(SIG_BLOCK, &mask, &prev); /* Block SIGCHLD */
if (Fork() == 0) /* Child */
exit(0);
/* Wait for SIGCHLD to be received */
pid = 0;
while (!pid)
Sigsuspend(&prev);
/* Optionally unblock SIGCHLD */
Sigprocmask(SIG_SETMASK, &prev, NULL);
/* Do some work after receiving SIGCHLD */
printf(".");
}
exit(0);
}
/* $end sigsuspend */
在另一个终端使用kill -9 processID杀死进程,得到以下消息,让我很困惑,为什么每个Reap child前面都有两个.?
Reap child 11880
..Reap child 11881
..Reap child 11882
..Reap child 11883
..Reap child 11884
..Reap child 11885
..Reap child 11886
..Reap child 11887
..Reap child 11888
..Reap child 11889
..Reap child 11890
..Reap child 11891
..Reap child 11892
..Reap child 11893
..Reap child 11894
..Reap child 11895
..Reap child 11896
..Reap child 11897
..Reap child 11898
..Reap child 11899
..Reap child 11900
Killed
然后,添加第 30 行 printf("Create child %d\n", getpid());
/* $begin sigsuspend */
#include "csapp.h"
volatile sig_atomic_t pid;
void sigchld_handler(int s)
{
int olderrno = errno;
pid = Waitpid(-1, NULL, 0);
printf("Reap child %d\n", pid);
errno = olderrno;
}
void sigint_handler(int s)
{
}
int main(int argc, char **argv)
{
sigset_t mask, prev;
Signal(SIGCHLD, sigchld_handler);
Signal(SIGINT, sigint_handler);
Sigemptyset(&mask);
Sigaddset(&mask, SIGCHLD);
while (1) {
Sigprocmask(SIG_BLOCK, &mask, &prev); /* Block SIGCHLD */
if (Fork() == 0) {/* Child */
printf("Create child %d\n", getpid()); //Line 30
exit(0);
}
/* Wait for SIGCHLD to be received */
pid = 0;
while (!pid)
Sigsuspend(&prev);
/* Optionally unblock SIGCHLD */
Sigprocmask(SIG_SETMASK, &prev, NULL);
/* Do some work after receiving SIGCHLD */
printf(".");
}
exit(0);
}
/* $end sigsuspend */
使用kill -9 processID 杀死另一个终端中的进程,得到的消息正是我所想象的。
Create child 15080
Reap child 15080
.Create child 15081
.Reap child 15081
.Create child 15082
.Reap child 15082
.Create child 15083
.Reap child 15083
.Create child 15084
.Reap child 15084
.Create child 15085
Killed
为什么只添加printf 行会产生如此大的差异?
【问题讨论】:
-
请不要在您显示的代码中包含行号。如果我们想自己尝试代码,复制它就会变得更加困难。如果要标记特定行,请在问题中提及它们,然后在这些行上添加 cmets。
-
@Some程序员老兄:谢谢你的建议,我已经编辑了代码。