我正在做一个程序,必须知道他的 child 在执行时是否出现段错误。
对于带核心转储和不带核心转储的段错误。对于第一个,我毫无问题地做到了,但我找不到是什么让我无法捕捉到这个信号。根据手册页,我应该收到 10,7,10,但我不确定这意味着什么,我只能尝试其中之一,但 10 和 7 都没有做任何事情
if (WTERMSIG(status) == 10)
my_putstr("Segmentation fault \n");
else if (WTERMSIG(status) == 11)
my_putstr("Segmentation fault (core dumped)\n");
最佳答案
您的问题有点不清楚,但您可以使用 WIFSIGNALED()
来检查子进程是否收到任何信号,如果 WIFSIGNALED(status)
为 true 则意味着子进程收到由任何信号异常终止。
if(fork() == 0 ) {
/*... */
/* send the exit status of child by calling exit()*/
}
else {
int status;
wait(&status);/* here parent collect exit status , now parent wants to know--> normal termination or abnormal */
if(WIFEXITED(status)) { /* true if terminates normally */
printf("normally terminates\n",WEXITSTATUS(status));
}
if(WIFSIGNALED(status)) { /* if child terminated bcz of any other signal */
printf("terminated by signal\n",WTERMSIG(status));// bcz of what signal
}
}
要观察子进程是否在没有核心转储的情况下接收到 SIGSEGV
,在上面的代码中,一旦子进程接收到 SIGSEGV
,您可以通过调用 sigaction()
设置信号处理程序> & 做一些事情。
关于c - 如何在没有核心转储的情况下捕获段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50077944/