forked from MeiK2333/apue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
12.8.c
63 lines (54 loc) · 1.27 KB
/
12.8.c
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <pthread.h>
#include "apue.h"
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg) {
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0) {
err_exit(err, "sigwait failed");
}
switch (signo) {
case SIGINT:
printf("\ninterrupt\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return (0);
default:
printf("unexpected signal %d\n", signo);
exit(1);
}
}
}
int main(void) {
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
err_exit(err, "SIG_BLOCK error");
}
err = pthread_create(&tid, NULL, thr_fn, 0);
if (err != 0) {
err_exit(err, "can't create thread");
}
pthread_mutex_lock(&lock);
while (quitflag == 0) {
pthread_cond_wait(&waitloc, &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) {
err_sys("SIG_SETMASK error");
}
exit(0);
}