【发布时间】:2019-09-26 10:43:57
【问题描述】:
我不明白为什么在第一次执行 kill 函数后 sleep 函数不会暂停父进程。 发送 SIGINT 后,会生成许多进程。此外,似乎生成了可变数量的进程。 清除待处理信号中的第一个 SIGINT 是否需要 SIGINT 处理程序?
void handler(int s) {
int status;
wait(&status);
printf("\n in the handler");
if (WIFSIGNALED(status)) {
int sig=WTERMSIG(status);
printf("\n child stopped by signal %d\n",sig);
}
if (WIFEXITED(status)) {
int ex=WEXITSTATUS(status);
printf("\n child stopped with exist status %d\n",ex);
}
}
int main() {
int pid,len, count, ret;
char s[1024];
signal(SIGCHLD,handler);
while(1) {
pid=fork();
if (pid==0) {
printf("\n Write something ");
scanf("%s",s);
len=strlen(s);
printf("\n Characters: %d",len);
return 1;
}
else {
sleep(20);
kill(pid,SIGINT);
}
}
}
【问题讨论】:
-
尝试使用
strace运行以查看发生了什么。 -
两个潜在问题。首先,您不能在信号处理程序中安全地调用
printf(),因为它不是异步信号安全的。有关示例问题,请参阅stackoverflow.com/questions/34467694/…。其次,你可能想usesigaction()instead ofsignal()。