Chinaunix首页 | 论坛 | 博客
  • 博客访问: 316810
  • 博文数量: 57
  • 博客积分: 146
  • 博客等级: 入伍新兵
  • 技术积分: 769
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-29 14:57
文章分类
文章存档

2014年(39)

2013年(13)

2012年(5)

我的朋友

分类: C/C++

2014-07-28 14:40:09

一.使用异步安全函数在信号处理函数中。

错误代码:

点击(此处)折叠或打开

  1. #include <signal.h>
  2. char *foo;
  3. void int_handler() {
  4. free(foo);
  5. _Exit(0);
  6. }
  7. int main(void) {
  8. foo = malloc(sizeof("Hello World."));
  9. if (foo == NULL) {
  10. /* handle error condition */
  11. }
  12. signal(SIGINT, int_handler);
  13. strcpy(foo, "Hello World.");
  14. puts(foo);
  15. free(foo);
  16. return 0;
  17. }



因为free不是异步安全函数,main函数执行free后,接收到信号并执行int_handler信号处理函数执行free操作,会导致double free的错误。

信号处理程序应尽可能简洁,理想情况下只设置flag并返回。
正确代码:

点击(此处)折叠或打开

  1. #include <signal.h>
  2. char *foo;
  3. void int_handler() {
  4. _Exit(0);
  5. }
  6. int main(void) {
  7. foo = malloc(sizeof("Hello World."));
  8. if (foo == NULL) {
  9. /* handle error condition */
  10. }
  11. signal(SIGINT, int_handler);
  12. strcpy(foo, "Hello World.");
  13. puts(foo);
  14. free(foo);
  15. return 0;
  16. }

二. sig_atomic_t
在处理信号(signal)的时候,有时对于一些变量的访问希望不会被中断,无论是硬件中断还是软件中断,这就要求访问或改变这些变量需要在计算机的一条指令内完成。通常情况下,int类型的变量通常是原子访问的,也可以认为 sig_atomic_t就是int类型的数据,因为对这些变量要求一条指令完成,所以sig_atomic_t不可能是结构体,只会是数字类型。
在linux里这样定义:
   typedef int __sig_atomic_t;

为了安全起见,无条件的信号处理程序应该使用sig_atomic_t类型


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