gpt4 book ai didi

c - 错误条件已修复,仍然在 C 中获取 SIGSEGV

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:08 25 4
gpt4 key购买 nike

在下面的代码中,我正在处理 SIGSEGV 信号并修复通过最小化绑定(bind)变量的错误条件。我想每当信号处理程序返回时,它都会重新启动信号发生期间的指令。在信号处理程序中,我最小化了绑定(bind)变量,但仍然得到 SIGSEGV 并进入无限循环

不知道哪里错了

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>

void SIG_segfault_handler(int);
static int bound = 5800000;

int main(int argc,char *argv[])
{
signal(SIGSEGV,SIG_segfault_handler);
puts("This is the driver code for experimenting with signal");
int *array = malloc(50);
*(array+ 23) = 78;
puts("-------------------------------------------------------------------------------------");
*(array + bound) = 100;
printf("Data: %d , %d \n",*(array + 23),*(array + bound));

puts("Initialiazed array with 50 bytes.. \n End of driver code. ");
//free(array);
return 0;
}

void SIG_segfault_handler(int signum)
{
puts("This is segmentation fault.. cannot continue with the memory operation.. aborting");
puts("Signal SIGSEGV is handled by the program");
puts("Fixing the error conditions..");
bound = 2;
}

最佳答案

根据 C 和 POSIX 标准,这是未定义的行为。不允许从 SIGSEGV 的信号处理程序返回。

参见 7.14.1.1 The signal function :

When a signal occurs and func points to a function, it is implementation-defined whether the equivalent of signal(sig, SIG_DFL); is executed or the implementation prevents some implementation-defined set of signals (at least including sig) from occurring until the current signal handling has completed; in the case of SIGILL, the implementation may alternatively define that no action is taken. Then the equivalent of (*func)(sig); is executed. If and when the function returns, if the value of sig is SIGFPE, SIGILL, SIGSEGV, or any other implementation-defined value corresponding to a computational exception, the behavior is undefined; otherwise the program will resume execution at the point it was interrupted.

执行信号处理程序后,执行会重新启动导致 SIGSEGV 的同一指令。这意味着当您溢出数组时(这会导致 SIGSEGV)将在返回后再次执行来自信号处理程序。这应该可以解释无限循环。

此外,您不应该从信号信号处理程序调用 puts();您只能从信号处理程序中调用异步信号安全函数。查看POSIX manual异步信号安全函数的列表。

由于各种实现提供的语义不同,也不鼓励使用 signal()。出于这个原因(以及其他原因),建议使用 sigaction()用于安装信号处理程序。

关于c - 错误条件已修复,仍然在 C 中获取 SIGSEGV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41286678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com