-
Notifications
You must be signed in to change notification settings - Fork 0
/
14_5.cpp
37 lines (33 loc) · 1.06 KB
/
14_5.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 用一个线程处理所有信号
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
#include<errno.h>
#define handle_error_en(en, msg) \
do{ errno = en; perror(msg); exit(EXIT_FAILURE); } while(0) // 这个define + while的用法好像哪里见过
static void *sig_thread(void* arg){
sigset_t *set = (sigset_t*) arg;
int s, sig;
for(;;){
// 第二个步骤,调用sigwait等待信号
s = sigwait(set, &sig);
if(s != 0){ handle_error_en(s, "sigwait"); }
printf("Signal handling thread got signal %d\n", sig);
}
}
int main(int argc, char* argv[]){
pthread_t thread;
sigset_t set;
int s;
// 第一个步骤,在主线程中设置信号掩码
sigemptyset(&set);
sigaddset(&set, SIGQUIT);
sigaddset(&set, SIGUSR1);
s = pthread_sigmask(SIG_BLOCK, &set, NULL);
if(s != 0){ handle_error_en(s, "pthread_sigmask"); }
s = pthread_create(&thread, NULL, &sig_thread, (void*)&set);
if(s != 0){ handle_error_en(s, "pthread_create"); }
pause();
}