同一信号具有多个信号处理程序是否有效? [英] Is it valid to have multiple signal handlers for same signal?
问题描述
我有两个共享库链接到我的测试应用程序.这两个库都具有SIGINT
的信号处理程序.
为同一信号设置多个信号处理程序是否有效?当我生成SIGINT
信号时,处理程序将执行哪个顺序?
正如其他人所说,只能设置一个信号处理程序,这是最后一个.然后,您将不得不自己管理调用两个函数. sigaction
函数可以返回以前安装的信号处理程序,您可以自己称之为. /p>
类似这样的东西(未经测试的代码):
/* 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);
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?
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);
这篇关于同一信号具有多个信号处理程序是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!