sigaction函数使用实例
?sigaction函數(shù)
(1)sigaction函數(shù)原型
sigaction函數(shù)用來查詢和設(shè)置信號(hào)處理方式,它是用來替換早期的signal函數(shù)。sigaction函數(shù)原型及說明如下:
| ???????????? sigaction(查詢和設(shè)置信號(hào)處理方式) |
?
?
| 所需頭文件 | #include <signal.h> | |
| 函數(shù)說明 | sigaction()會(huì)依參數(shù)signum指定的信號(hào)編號(hào)來設(shè)置該信號(hào)的處理函數(shù) | |
| 函數(shù)原型 | int sigaction(int signum,const struct sigaction *act ,struct sigaction *oldact) | |
| 函數(shù)傳入值 ? | signum | 可以指定SIGKILL和SIGSTOP以外的所有信號(hào) |
| act | 參數(shù)結(jié)構(gòu)sigaction定義如下 struct sigaction { void (*sa_handler) (int); void? (*sa_sigaction)(int, siginfo_t *, void *); sigset_t sa_mask; int sa_flags; void (*sa_restorer) (void); } ①??? sa_handler:此參數(shù)和signal()的參數(shù)handler相同,此參數(shù)主要用來對(duì)信號(hào)舊的安裝函數(shù)signal()處理形式的支持 ②??? sa_sigaction:新的信號(hào)安裝機(jī)制,處理函數(shù)被調(diào)用的時(shí)候,不但可以得到信號(hào)編號(hào),而且可以獲悉被調(diào)用的原因以及產(chǎn)生問題的上下文的相關(guān)信息。 ③??? sa_mask:用來設(shè)置在處理該信號(hào)時(shí)暫時(shí)將sa_mask指定的信號(hào)擱置 ④??? sa_restorer: 此參數(shù)沒有使用 ⑤??? sa_flags:用來設(shè)置信號(hào)處理的其他相關(guān)操作,下列的數(shù)值可用。可用OR 運(yùn)算(|)組合 ??? A_NOCLDSTOP:如果參數(shù)signum為SIGCHLD,則當(dāng)子進(jìn)程暫停時(shí)并不會(huì)通知父進(jìn)程 ??? SA_ONESHOT/SA_RESETHAND:當(dāng)調(diào)用新的信號(hào)處理函數(shù)前,將此信號(hào)處理方式改為系統(tǒng)預(yù)設(shè)的方式 ??? SA_RESTART:被信號(hào)中斷的系統(tǒng)調(diào)用會(huì)自行重啟 ??? SA_NOMASK/SA_NODEFER:在處理此信號(hào)未結(jié)束前不理會(huì)此信號(hào)的再次到來 ??? SA_SIGINFO:信號(hào)處理函數(shù)是帶有三個(gè)參數(shù)的sa_sigaction | |
| oldact | 如果參數(shù)oldact不是NULL指針,則原來的信號(hào)處理方式會(huì)由此結(jié)構(gòu)sigaction返回 | |
| 函數(shù)返回值 | 成功:0 | |
| 出錯(cuò):-1,錯(cuò)誤原因存于error中 | ||
| 附加說明 | 信號(hào)處理安裝的新舊兩種機(jī)制: ①???? 使用舊的處理機(jī)制:struct sigaction act;? act.sa_handler=handler_old; ②???? 使用新的處理機(jī)制:struct sigaction act; act.sa_sigaction=handler_new; 并設(shè)置sa_flags的SA_SIGINFO位 | |
| 錯(cuò)誤代碼 | EINVAL:參數(shù)signum不合法,或是企圖攔截SIGKILL/SIGSTOP信號(hào) EFAULT:參數(shù)act,oldact指針地址無法存取 EINTR:此調(diào)用被中斷 | |
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
void new_op(int, siginfo_t *, void *);?
int main(int argc, char** argv)
{
? ? struct sigaction act;
? ? int sig;
? ? sig = atoi(argv[1]);
? ? sigemptyset(&act.sa_mask);
? ? act.sa_flags=SA_SIGINFO;
? ? act.sa_sigaction=new_op;
? ? if (sigaction(sig, &act, NULL)<0)
? ? { ??
? ? ? ? perror("install sigal error");
? ? ? ? return -1;?
? ? } ??
? ? while(1)
? ? { ??
? ? ? ? sleep(2);
? ? ? ? printf("wait for the signal\n");
? ? } ??
? ? return 0;
}
void new_op(int signum, siginfo_t *info, void *myact)
{
? ? printf("receive signam %d\n", signum);
? ? sleep(5);
}
gcc sigaction_t1.c -o sigaction_t1 -g
#./sigaction_t1 1
wait for the signal
wait for the signal
#./sigaction_t1 2
wait for the signal
wait for the signal
wait for the signal
receive signam 2
#
總結(jié)
以上是生活随笔為你收集整理的sigaction函数使用实例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。