转自:http://hi.baidu.com/phps/blog/item/b064b7b71944cff630add1b4.html
上面说了那么多结构体和复杂的很的siginfo,其实siginfo我们在实际应用中并不需要去初始化他或者做什么,只是在信号触发时我们可以从这个结构体中提取一些信息
说了这么多我们可以小试牛刀了
自己写一个程序
[root@localhost clang]# cat f4.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
void test(int n,struct siginfo *siginfo,void *myact)
{
printf("signal number:%d/n",n);/** 打印出信号值 **/
printf("siginfo signo:%d/n",siginfo->si_signo); /** siginfo结构里保存的信号值 **/
printf("siginfo errno:%d/n",siginfo->si_errno); /** 打印出错误代码 **/
printf("siginfo code:%d/n",siginfo->si_code); /** 打印出出错原因 **/
}
int main(void)
{
/** install signal use sigaction **/
struct sigaction act;
sigemptyset(&act.sa_mask); /** 清空阻塞信号 **/
act.sa_flags=SA_SIGINFO; /** 设置SA_SIGINFO 表示传递附加信息到触发函数 参见注释1**/
act.sa_sigaction=test; /*设置信号处理函数*/
if(sigaction(SIGINT,&act,NULL) < 0)
{
printf("install signal error/n");
}
while(1)
{
sleep(1);
printf("wait for the signal/n");
}
}
[root@localhost clang]#
[root@localhost clang]# ./test
wait for the signal
wait for the signal
wait for the signal
wait for the signal
signal number:2
siginfo signo:2
siginfo errno:0
siginfo code:128
wait for the signal
wait for the signal
wait for the signal
signal number:2
siginfo signo:2
siginfo errno:0
siginfo code:128
wait for the signal
[2]+ Stopped ./test
[root@localhost clang]# kill %1
[1]- Stopped vim f4.c
[root@localhost clang]#
可以看到当按下CTRL+C结束程序时信号将触发执行test函数
注释1:
SA_SIGINFO
If cleared and the signal is caught, the signal-catching function shall be entered as:
void func(int signo);
where signo is the only argument to the signal-catching function. In this case, the application
shall use the sa_handler member to describe the signal-catching function and the application shall
not modify the sa_sigaction member.
If SA_SIGINFO is set and the signal is caught, the signal-catching function shall be entered as:
void func(int signo, siginfo_t *info, void *context);
where two additional arguments are passed to the signal-catching function. The second argument
shall point to an object of type siginfo_t explaining the reason why the signal was generated; the
third argument can be cast to a pointer to an object of type ucontext_t to refer to the receiving
process/u2019 context that was interrupted when the signal was delivered. In this case, the application
shall use the sa_sigaction member to describe the signal-catching function and the application
shall not modify the sa_handler member.
摘自man sigaction