对多个信号具有单个信号处理程序功能的正确方法是什么? [英] What is correct way to have single Signal Handler function for multiple Signals?

查看:130
本文介绍了对多个信号具有单个信号处理程序功能的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux上的C语言中,最好的方法是设置一个程序来处理具有相同功能的多个POSIX信号?

What is the best way in C on Linux for setting up a program that can handle multiple POSIX-signals with the same function?

例如,在我的代码中,我有一个处理函数,当捕获到信号以执行某些操作时,我想一般调用该处理函数:

For example in my code I have a handler function that I want to generically call when ever a signal is caught to perform some actions:

/* Exit handler function called by sigaction */
void exitHandler( int sig, siginfo_t *siginfo, void *ignore )
{
  printf("*** Got %d signal from %d\n", siginfo->si_signo, siginfo->si_pid);
  loopCounter=0;

  return;
}

我通过为每个信号进行单独的信号调用来设置两个信号来捕获:

I have set up two signals to catch by having individual sigaction calls for each signal:

/* Set exit handler function for SIGUSR1 , SIGINT (ctrl+c) */
struct sigaction act;
act.sa_flags = SA_SIGINFO;
act.sa_sigaction = exitHandler;
sigaction( SIGUSR1, &act, 0 );
sigaction( SIGINT, &act, 0 );

这是设置此类处理的正确方法吗?还有什么其他方法可以让我不必枚举所有可能的信号编号吗?

Is this the correct way to set up this type of handling? Is there any other way where I don't have to enumerate all the possible signal numbers?

推荐答案

我看不到如何直接为 all 信号设置单个处理程序.但是,您可以使用 sigfillset() 生成一个包含所有有效信号编号的集合,然后使用

I can't see how you can straightforwardly set a single handler for all signals. However, you can get fairly close by using sigfillset() to generate a set containing all valid signal numbers, and then iterate over possible signal numbers using sigismember() to determine whether that number is in the set, and set a handler if so. OK, I can't see a method of determining what the maximum possible signal number is, so you might have to guess a suitable maximum value.

这篇关于对多个信号具有单个信号处理程序功能的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆