如何使用" SIGALTSTACK"在信号处理程序? [英] how to use "sigaltstack" in signal handler program?
问题描述
做谁知道如何使用 SIGALTSTACK 在一个真实的信号处理程序,简单但完整的code可以对我帮助很大!
预先感谢您!
did anyone who knows how to use the sigaltstack in a real signal handler program,a simple but complete code may be great help to me! thank you in advance!
推荐答案
下面是一个使用 SIGALTSTACK
赶上无限递归最小的示例程序。如果您注释掉 SIGALTSTACK
来电或 SA_ONSTACK
标志,信号处理程序将无法运行,因为它没有栈左,程序会崩溃。
Here is a minimal sample program that uses sigaltstack
to catch infinite recursion. If you comment out the sigaltstack
call or SA_ONSTACK
flag, the signal handler will not be able to run because it has no stack left and the program will just crash.
#define _XOPEN_SOURCE 700
#include <signal.h>
#include <unistd.h>
void handler(int sig)
{
write(2, "stack overflow\n", 15);
_exit(1);
}
unsigned infinite_recursion(unsigned x) {
return infinite_recursion(x)+1;
}
int main()
{
static char stack[SIGSTKSZ];
stack_t ss = {
.ss_size = SIGSTKSZ,
.ss_sp = stack,
};
struct sigaction sa = {
.sa_handler = handler,
.sa_flags = SA_ONSTACK
};
sigaltstack(&ss, 0);
sigfillset(&sa.sa_mask);
sigaction(SIGSEGV, &sa, 0);
infinite_recursion(0);
}
一个更复杂的使用可能会实际执行 siglongjmp
跳出信号处理和回哪里可避免无限递归的一个点。如果正在使用异步信号不安全库调用这是无效的,或者如果你的数据可能会在一个不安全/不可恢复的状态留,但如果你正在执行的纯算术计算,也可能是有效的。
A more sophisticated use might actually perform siglongjmp
to jump out of the signal handler and back to a point where the infinite recursion can be avoided. This is not valid if async-signal-unsafe library calls are being used, or if your data might be left in an unsafe/unrecoverable state, but if you're performing pure arithmetic computations, it may be valid.
也许对于信号处理一个更好的任务将是执行,这不是已经保存到磁盘上任何有价值/关键数据的紧急转储。这可能是困难的,如果你不能叫异步信号不安全的功能,但如果你把一些精力它通常是可能的。
Perhaps a better task for the signal handler would be performing an emergency dump of any valuable/critical data that wasn't already saved to disk. This could be difficult if you can't call async-signal-unsafe functions, but it's usually possible if you put some effort into it.
这篇关于如何使用&QUOT; SIGALTSTACK&QUOT;在信号处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!