C语言trap 可重入和线程安全

7 篇文章 0 订阅
3 篇文章 0 订阅
#include <signal.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>


void handler(int signum)
{
        char result[100];
        time_t now;
//      struct tm time1;


        now = time(NULL);
//      localtime_r(&now, &time1);
//      ctime_r(&now,result);
        strcpy(result,ctime(&now));
//      strftime(result, 100, "%T", &time1);
        printf("At %s, user pressed Ctrl-C\n", result);
}


int main (void)
{
        time_t now;
//      struct tm ltime;
        char result[100];


        if (signal(SIGINT, handler) == SIG_IGN)
                signal(SIGINT, SIG_IGN);


        now = time(NULL);
        while(1) {
#ifdef UNSAFE
        //      localtime_r(&now, <ime);
                ctime(&now);
#endif
        }


        return 0;
}

 对于信号处理函数,尽量做到简单,如果调用了不可重入函数,可能引发死锁问题。

#16 0x0000003257e7230f in _int_free () from /lib64/libc.so.6
#17 0x0000003257e7276b in free () from /lib64/libc.so.6
#18 0x0000003257e8c7ca in tzset_internal () from /lib64/libc.so.6
#19 0x0000003257e8cf2e in __tz_convert () from /lib64/libc.so.6
#20 0x0000003257e8b529 in ctime () from /lib64/libc.so.6
strace -p 1202
Process 1202 attached - interrupt to quit
futex(0x3258154fc0, FUTEX_WAIT_PRIVATE, 5, NULL


gcc -D UNSAFE test1.c -o test_unsafe

gcc -D UNSAFE test1.c -o test

编译上面这个程序可以重现这个问题。


线程中也不要调用非线程安全系统调用,否则也会出现死锁。

关于futex的文章

http://www.cnblogs.com/yysblog/archive/2012/11/03/2752728.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值