c - 如何在没有核心转储的情况下捕获段错误

标签 c segmentation-fault

我正在做一个程序,必须知道他的 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/

相关文章:

生成 "zsh segmentation fault"的C代码

c - 在 C/Linux 中,您如何从系统中找到程序内存/分段的界限?

c - C中的链表程序

c - 运行代码时出现奇怪的错误/结果...C fdtd 方法

c - 警告 : format ‘%d’ expects argument of type ‘int *’ , 但参数 3 的类型为‘uint8_t * {aka unsigned char *}

C - 函数内的动态分配/重定位

读/写 NETLINK 套接字会失败吗?

C语言。 TCP 服务器-客户端,字符串传递错误

C rand() 函数不生成随机数

python - 我如何处理追溯到杀死我的 worker 的段错误?