1
|
#include <unistd.h>
|
2
|
#include <errno.h>
|
3
|
#include <fcntl.h>
|
4
|
#include <sys/stat.h>
|
5
|
#include <string.h>
|
6
|
|
7
|
#include <stdio.h>
|
8
|
|
9
|
#include <signal.h>
|
10
|
|
11
|
#include <pthread.h>
|
12
|
#include <semaphore.h>
|
13
|
|
14
|
sem_t* semaphore;
|
15
|
volatile sig_atomic_t received_signum;
|
16
|
|
17
|
void handler(int signum) {
|
18
|
|
19
|
|
20
|
received_signum = signum;
|
21
|
sem_post(semaphore);
|
22
|
|
23
|
|
24
|
}
|
25
|
|
26
|
void installTerminationRequestHandler() {
|
27
|
if (SEM_FAILED == (semaphore = sem_open("rscterminate", O_CREAT | O_EXCL, 0644, 0))) {
|
28
|
printf("%d, %s\n", errno, strerror(errno)); _exit(1);
|
29
|
}
|
30
|
|
31
|
|
32
|
struct sigaction action;
|
33
|
action.sa_handler = &handler;
|
34
|
sigemptyset(&action.sa_mask);
|
35
|
action.sa_flags = SA_RESETHAND;
|
36
|
sigaction(SIGINT, &action, 0);
|
37
|
sigaction(SIGTERM, &action, 0);
|
38
|
}
|
39
|
|
40
|
int waitForTerminationRequest() {
|
41
|
while ((-1 == sem_wait(semaphore)) && (errno == EINTR));
|
42
|
printf("%d, %s\n", errno, strerror(errno));
|
43
|
return received_signum;
|
44
|
}
|
45
|
|
46
|
void* just_sleep(void* data) {
|
47
|
while (1) {
|
48
|
printf("still running\n");
|
49
|
sleep(1);
|
50
|
}
|
51
|
}
|
52
|
|
53
|
int main() {
|
54
|
|
55
|
installTerminationRequestHandler();
|
56
|
|
57
|
pthread_t thread[1];
|
58
|
pthread_create(&thread[0], 0, &just_sleep, 0);
|
59
|
printf("created thread %d\n", (int) thread[0]);
|
60
|
|
61
|
printf("before wait\n");
|
62
|
printf("after_wait; signum %d\n", waitForTerminationRequest());
|
63
|
|
64
|
}
|