简体   繁体   English

最终解决分段错误(C ++)

[英]Finally Block for Segmentation Faults (C++)

I'm using ncurses and whenever I get a segfault, ncurses doesn't properly release control of the terminal (because endwin() was never called). 我正在使用ncurses,并且每当遇到段错误时,ncurses都不会正确释放终端的控制权(因为从未调用过endwin())。 I set up a signal handler: 我设置了一个信号处理程序:

void handler(int signum) {
    endwin();
    exit(EXIT_FAILURE);
}

but the problem with this is that the segfault is ignored, as opposed to delayed until after endwin(). 但是这样做的问题是,segfault被忽略,而不是延迟到endwin()之后。 I'm fairly new to C++; 我是C ++的新手。 can segfaults be caught like exceptions, so that I could have a finally block? segfaults是否可以像异常一样被捕获,以便我可以有一个finally块? Or is there someway to resend the segfault from inside the handler? 还是有某种方法可以从处理程序内部重新发送段错误?

Segfault is undefined behavior. 段错误是未定义的行为。 You must find it and fix it. 您必须找到并修复它。 Don't worry about ncurses not releasing the terminal, and find and fix the bug. 不必担心ncurses不会释放终端,并查找并修复错误。

From the signal man page: 信号手册页:

According to POSIX, the behavior of a process is undefined after it ignores a SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill(2) or raise(3). 根据POSIX,在忽略不由kill(2)或raise(3)生成的SIGFPE,SIGILL或SIGSEGV信号之后,进程的行为是不确定的。

Trying to do anything after a seg fault is crazy. 在段错误后尝试执行任何操作都是疯狂的。 It's like the air-bag in your activating after a crash and you keep on driving, because, well, you have an air bag and it will keep you safe in a crash. 这就像安全气囊在撞车后处于激活状态并继续行驶一样,因为好了,您有一个安全气囊,它将在撞车时保持安全。 Papering over this with a handler is not the way. 用处理程序来解决这个问题不是办法。

One way would be to make your program take input from a file or stub out the output. 一种方法是使程序从文件中获取输入或将输出存根。 You could also try remotely attaching to a process with gdb . 您也可以尝试使用gdb远程附加到进程 Never done it but it might be worth a try. 没做过,但是值得一试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM