Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

c - How to use "sigaltstack" in signal handler program?

Do anyone know how to use the sigaltstack in a real signal handler program? A simple but complete code may be great help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", 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);
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...