C語言trap 可重入和線程安全

#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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章