#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
长戟十三千 阅读(426)
评论(0) 编辑 收藏 引用 所属分类:
编程技巧随笔