Chinaunix首页 | 论坛 | 博客
  • 博客访问: 239069
  • 博文数量: 35
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 273
  • 用 户 组: 普通用户
  • 注册时间: 2014-11-27 23:34
个人简介

To follow the path,look to the master,follow the master.

文章分类

全部博文(35)

文章存档

2019年(1)

2018年(1)

2017年(1)

2016年(8)

2015年(24)

分类: LINUX

2016-01-08 09:45:12

信号:一种软中断

typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler)
在调用进程中设置信号的处理方式
signum:信号
handler:信号处理方式 SIG_IGN(忽略),SIG_DFL(默认) 自定义函数
返回值:成功= 失败=SIG_ERR    返回该信号上次处理函数

kill -l 查看信号编号

点击(此处)折叠或打开

  1. #include "../apue.h"
  2. sighandler_t ret;
  3. void sig_fun1(int signum)
  4. {
  5.     printf("[%d]%s\n", getpid(), __FUNCTION__);
  6.     ret=signal(SIGALRM, ret);
  7.     printf("[%s]ret=0x%x\n",__FUNCTION__,ret);
  8.     return;
  9. }
  10. void sig_fun2(int signum)
  11. {
  12.     printf("[%d]%s\n", getpid(), __FUNCTION__);
  13.     ret=signal(SIGALRM, ret);
  14.     printf("[%s]ret=0x%x\n",__FUNCTION__,ret);
  15.     return;
  16. }
  17. int main()
  18. {
  19.     int i;
  20.     
  21.     printf("[%s]pid=%d fun1=%p fun2=%p\n",
  22.      __FUNCTION__, getpid(), sig_fun1, sig_fun2);//打印该执行函数名,进程id, sig_fun1、sig_fun2的函数地址
  23.     
  24.     for(i=0; i<5; i++)
  25.     {
  26.         printf("wait...%d\n", i+1);
  27.         sleep(2);
  28.     }

  29.     ret=signal(SIGALRM, sig_fun1);//设置SIGALRM 信号, 信号处理函数sig_fun1
  30.     printf("ret=0x%x\n",ret);

  31.     for(; i<10; i++)
  32.     {
  33.         printf("wait...%d\n", i+1);
  34.         sleep(2);
  35.     }
  36.     
  37.     ret=signal(SIGALRM, sig_fun2);
  38.     printf("ret=0x%x\n",ret);

  39.     while(1)
  40.     {
  41.         ;
  42.     }

  43.     return 0;
  44. }
执行结果如下:
[root@bogon 04_signal]# ./exe
[main]pid=3195 fun1=0x8048454 fun2=0x80484b4
wait...1
wait...2
wait...3
wait...4
wait...5
ret=0x0
wait...6
wait...7
wait...8
wait...9
wait...10
ret=0x8048454
[3195]sig_fun2
[sig_fun2]ret=0x80484b4
示例1

我们在设置 把sig_fun2  设置Alarm 信号 的处理函数 后 ,执行
[root@bogon 04_signal]# kill -14 3195
[root@bogon 04_signal]#
示例2
此处是向 进程id  3195 发送 Alarm 信号就会执行 sig_fun2函数,出现示例1


阅读(1521) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~