免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1456 | 回复: 0
打印 上一主题 下一主题

线程信号处理的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-11-29 11:07 |只看该作者 |倒序浏览
之前用信号都是在进程中用的,最近的作业要用到线程的信号处理,自己写了个测试程序,结果很诡异,希望懂行的给指点一二
测试程序的流程是在主线程中安装信号处理句柄,然后创建几个线程,然后主线程向子线程发信号,子线程退出,代码是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <pthread.h>
#include <signal.h>

#define THREADS 4
#define erraise(string) do{\
    perror(string);\
    exit(-1);\
}while(0)


void *thread_func(void *argv)
{
    while(1);
    return (void *)0;
}

void handler(int sig, siginfo_t *si, void *unused)
{
    printf("Signal recieved!\n");
    pthread_exit((void *)0);
}
int main()
{
    pthread_t thread[THREADS];
    struct sigaction sa;
    sa.sa_flags = SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = handler;
    sigaction(SIGUSR1, &sa, NULL);
    int i;
    for (i = 0; i < THREADS; i++)
    {
        pthread_create(&thread[i], NULL, thread_func, NULL);
        printf("thread %lu created!\n", thread[i]);
    }
    printf("Father thread: %lu\n", (unsigned long)pthread_self());
    for (i = 0; i < THREADS; i++)
        pthread_kill(thread[i], SIGUSR1);
    for (i = 0; i < THREADS; i++)
    {
        pthread_join(thread[i], NULL);

        printf("Thread %lu recieved signal and exited!\n", thread[i]);
    }
    printf("Father thread exit!\n");
    return 0;
}

运行多次,大部分情况下,程序运行会出现断错误:
thread 3078339440 created!
thread 3069946736 created!
thread 3061554032 created!
thread 3053161328 created!
Father thread: 3078342336
Signal recieved!
Signal recieved!
Signal recieved!
Signal recieved!
Segmentation fault

不过少数情况下结果是正确的(四个子线程都正常退出),也就是说我的程序结果是不确定的,有人知道是什么情况吗?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP