Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - Is it valid to have multiple signal handlers for same signal?

I have two shared libraries linked to my test application. Both of the libraries have signal handlers for SIGINT.

Is it valid to have multiple signal handlers for same signal? Which order the handlers will execute when I generate a SIGINT signal?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

As said by others, only one signal handler can be set, which is the last one. You would then have to manage calling two functions yourself. The sigaction function can return the previously installed signal handler which you can call yourself.

Something like this (untested code):

/* other signal handlers */
static void (*lib1_sighandler)(int) = NULL;
static void (*lib2_sighandler)(int) = NULL;

static void aggregate_handler(int signum)
{
    /* your own cleanup */
    if (lib1_sighandler)
        lib1_sighandler(signum);
    if (lib2_sighandler)
        lib2_sighandler(signum);
}

... (later in main)
struct sigaction sa;
struct sigaction old;

lib1_init(...);
/* retrieve lib1's sig handler */
sigaction(SIGINT, NULL, &old);
lib1_sighandler = old.sa_handler;

lib2_init(...);
/* retrieve lib2's sig handler */
sigaction(SIGINT, NULL, &old);
lib2_sighandler = old.sa_handler;

/* set our own sig handler */
memset(&sa, 0, sizeof(sa));
sa.sa_handler = aggregate_handler;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...