我的代码C Unix出了问题。我将复制关键部分: 所以在第一个sigprocmask之后我发送一个信号,在SIG_UNBLOCK之后,没有工作前一个句柄(gestisciSignalDopoReg)而不是标准句柄来管理我的信号,所以它只是终止进程......出了什么问题?感谢
struct sigaction gestoreSegnale;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask,SIGTERM);
sigaddset(&mask,SIGINT);
sigaddset(&mask,SIGALRM);
sigaddset(&mask,SIGQUIT);
sigaddset(&mask,SIGHUP);
sigaddset(&mask,SIGSEGV);
sigaddset(&mask,SIGILL);
sigaddset(&mask,SIGPIPE);
void setSegnali(int segn,__sighandler_t handler){
gestoreSegnale.sa_handler=handler;
gestoreSegnale.sa_mask=mask;
sigaction(segn, &gestoreSegnale, NULL);
}
void eseguiSetSegnali(__sighandler_t handler){
setSegnali(SIGQUIT, handler);
setSegnali(SIGSEGV, handler);
setSegnali(SIGILL, handler);
setSegnali(SIGHUP, handler);
setSegnali(SIGTERM, handler);
setSegnali(SIGINT, handler);
}
void main(){
eseguiSetSegnali(gestisciSIGNALDopoReg);
sigprocmask(SIG_BLOCK,&mask,NULL);
.........other part of code.........
sigprocmask(SIG_UNBLOCK,&mask,NULL);
}
请!我需要帮助!
答案 0 :(得分:3)
您没有初始化sa_flags
的{{1}}字段,因此它可能包含垃圾值。有可能设置了struct sigaction
位,根据手册页将为您提供此行为:
SA_RESETHAND
如果你的信号处理程序运行了一次,那么它将被清除并返回默认值,所以你可能只需将标记清零,如:
SA_RESETHAND
Restore the signal action to the default state once the signal handler has been called. This flag is
only meaningful when establishing a signal handler. SA_ONESHOT is an obsolete, non-standard synonym
for this flag.
无论如何,以下小例子有效:
void setSegnali(int segn,__sighandler_t handler){
gestoreSegnale.sa_handler=handler;
gestoreSegnale.sa_mask=mask;
/* Make sure to clear flags */
gestoreSegnale.sa_flags=0;
sigaction(segn, &gestoreSegnale, NULL);
}
如果运行,您会看到所需的结果:
#include <signal.h>
#include <stdio.h>
void handler(int sig) {
printf("HUP %d\n", sig);
}
void main(){
struct sigaction act;
/* Block SIGHUP while the signal handler is running */
sigemptyset(&act.sa_mask);
sigaddset(&act.sa_mask,SIGHUP);
/* Define handler for signal */
act.sa_handler = handler;
/* Clear flags */
act.sa_flags = 0;
act.sa_restorer = NULL;
/* Install handler for SIGHUP */
sigaction(SIGHUP, &act, NULL);
/* Set mask to block SIGHUP */
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGHUP);
/* Block SIGHUP */
printf("Blocking SIGHUP\n");
sigprocmask(SIG_BLOCK,&mask,NULL);
printf("Sleeping\n");
sleep(60);
/* Unblock SIGHUP */
printf("Unblocking SIGHUP\n");
sigprocmask(SIG_UNBLOCK,&mask,NULL);
printf("Sleeping again\n");
while(1)
sleep(60);
}