[英]How do I make child print the signal that killed it?
我有以下代码,其中父级创建多个子进程并随后将其杀死。 一旦被杀死,我想打印杀死孩子的东西(在这种情况下为信号)。 但是,代码并没有打印出来。 似乎是什么问题?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
int i;
static void signal_handler(int signo)
{
if (signo == SIGUSR1)
{
printf("child %d received sigusr1\n", i + 1);
}
}
int main(void)
{
char buff[50];
int status;
if (signal(SIGUSR1, signal_handler) == SIGUSR1)
{
perror("Signal handling error");
}
pid_t cpid, count;
for (i = 0; i < 5; i++)
{
cpid = fork();
if (cpid == 0)
{
sleep(10);
//exit(0);
}
else if (cpid > 0)
{
kill(cpid, SIGUSR1);
int status;
int n = waitpid(cpid, &status, 0);
if (n != cpid)
{
perror("error");
}
if (WIFSIGNALED(status))
{ /* get WTERMSIG(status) */
printf("killed by signal=%d\n", WTERMSIG(status));
}
}
else
{
perror("Fork error: ");
exit(1);
}
}
}
WIFSIGNALED(stat_val)-如果由于接收到未捕获到的信号而终止的子进程返回状态,则评估为非零值
您的信号被捕获(在退出之前收到信号)。
您还有其他人提到的其他问题。
使用waitpid
代替,并且一定要同时处理正常退出并杀害按信号:
pid_t pid = fork();
if (pid == 0)
{
exit(0);
}
else if (pid > 0)
{
int status;
int n = waitpid(pid, &status, 0);
if (n != pid) { /* error */ }
else if (WIFSIGNALED(status)) { /* get WTERMSIG(status) */ }
else if (WIFEXITED(status)) { /* get WEXITSTATUS(status) */ }
}
else if (pid < 0)
{
/* error */
}
从文档中可以看到, wait
将等待任何孩子,而不仅仅是当前孩子。 当然,孩子完全有可能在接收到信号之前正常退出。
您可以通过调用pause
来阻止孩子正常退出,但是该信号只会在不处理孩子的情况下将其杀死。 如果信号处理程序返回,则pause
也会返回。
这是您应用的实际代码吗?
printf("killed by signal=%d\n");
WTERMSIG(status);
如果是这样,第二行无效,请尝试将其更改为:
printf("killed by signal=%d\n", WTERMSIG(status));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.