随笔 - 137  文章 - 1  trackbacks - 0
<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿

随笔分类

随笔档案

收藏夹

调试技巧

搜索

  •  

最新评论

阅读排行榜

评论排行榜

#include<stdio.h>
#include<pthread.h>
#include<signal.h>
#include<setjmp.h>
#include<errno.h>

static sigjmp_buf env;
pthread_t thread;

void alarm_handler(int sig){
        siglongjmp(env, -1);
        printf("alarm_handler\n");
        return;
}

void threadtest(){
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGALRM);
    sigprocmask(SIG_UNBLOCK, &set, NULL);
    struct sigaction act,oldact;
    act.sa_handler = alarm_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags |= SA_INTERRUPT;
    sigaction(SIGALRM, &act, &oldact);
    if(sigsetjmp(env, 1) != 0){
        printf("sigsetjmp\n");
        alarm(0);
        sigaction(SIGALRM, &oldact, NULL);
        sigprocmask(SIG_BLOCK, &set, NULL);  //还不行就使用pthread_sigmask(SIG_UNBLOCK, &set, NULL);
        return;
    }
    alarm(2);
    printf("sleep before\n");
    int i = 1;
    while(i<= 10) {
        printf("i = %d\n",i++);
        sleep(1);
    }
    printf("sleep end\n");
    alarm(0);
    sigaction(SIGALRM, &oldact, NULL);
    sigprocmask(SIG_BLOCK, &set, NULL);  //还不行就使用pthread_sigmask(SIG_UNBLOCK, &set, NULL);
    return;
}

int main(){
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGALRM);
    sigprocmask(SIG_BLOCK, &set, NULL);
    int err = 1;
    threadtest();  //函数调用
   while(err <= 3) {
         printf("err = %d\n",err++);
         sleep(1);
    }
    putchar('\n');
        
    pthread_create(&thread,NULL,(void *)threadtest,NULL);   //用线程的方式
   err = 1;
    while(err <= 5) {
        printf("err = %d\n",err++);
        sleep(1);
    }
    pthread_join(thread,NULL);
}
posted on 2018-06-14 15:27 长戟十三千 阅读(400) 评论(0)  编辑 收藏 引用 所属分类: 编程技巧随笔

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理