精通
英语
和
开源
,
擅长
开发
与
培训
,
胸怀四海
第一信赖
锐英源精品开源心得,转载请注明:“锐英源www.wisestudy.cn,孙老师作品,电话13803810136。需要全文内容也请联系孙老师。
#include <signal.h>1. Eitheractor oact may be NULL. Eitheractor oact 可能是NULL。
intsigaction(intsigno, const structsigaction*act,
structsigaction*oact);
structsigaction{
void (*sa_handler)(int);/* SIG_DFL, SIG_IGN or pointer to function */
sigset_tsa_mask;/* additional signals to be blocked during execution of handler */
intsa_flags;/*special flags and options */
void(*sa_sigaction) (int, siginfo_t*, void *);/* real-time handler */ };
Example: Set up Signal Handler for SIGINT 例子:设置信号处理程序为SIGINT
structsigactionnewact;
newact.sa_handler= mysighand; /*set new handler*/设立新的处理程序
newact.sa_flags= 0;/* no special options *// / *没有特殊选项
if ((sigemptyset(&newact,sa_mask)== -1) ||
(sigaction(SIGINT, &newact, NULL)== -1))
perror(“Failedto install SIGINT signal handler”);
Set up Signal Handler that Catches SIGINT Generated by Ctrl-C 设置信号处理程序,捕捉按Ctrl-C生成的SIGINT
void catchctrlc(intsigno){Note: write is async-signal safe –meaning it can be called inside a signal handler. Not so for print for strlen.
char handmsg[] = "I found Ctrl-C\n";
intmsglen= sizeof(handmsg);
write(STDERR_FILENO, handmsg, msglen);
}
…
structsigactionact;
act.sa_handler= catchctrlc;
act.sa_flags= 0;
if ((sigemptyset(&act.sa_mask)== -1) ||
(sigaction(SIGINT, &act, NULL)== -1))
perror("Failedto set SIGINT to handle Ctrl-C");
Signals provide method for waiting for event without busy waiting 信号提供不忙碌等待事件的方法
sigsuspend
sigsuspendfunction sets signal mask and suspends process until signal is caughtby the process sigsuspend函数设置信号掩码,直到信号被处理捕获暂停过程
sigsuspend returns when signal handler of the caught signal returns. 当时已捕获信号的信号处理程序返回,sigsuspend返回
#include <signal.h>
intsigsupend(constsigset_t*sigmask);
Example: sigsuspend
What’s wrong?
sigfillset(&sigmost);
sigdelset(&sigmost, signum);
sigsuspend(&sigmost);
如果信号是代码段开始前递送的signum,这个过程仍然自己暂停,并且另外一个锁定的signum不会产生。
Example: sigsuspend(Correct Way to Wait for Single Signal) 例如:sigsuspend(正确的方式等待单次信号)
static volatile sig_atomic_tsigreceived=0;
/*assume signal handler has been setup for signumand it sets sigreceived=1*/
sigset_tmaskall, maskmost, maskold;
intsignum= SIGUSR1;
sigfillset(&maskall);
sigfillset(&maskmost);
sigdelset(&maskmost, signum);
sigprocmask(SIG_SETMASK, &maskall, &maskold);
if (sigreceived== 0)
sigsuspend(&maskmost);
sigprocmask(SIG_SETMASK, &maskold, NULL);