-
Notifications
You must be signed in to change notification settings - Fork 307
/
10.17.c
100 lines (78 loc) · 1.76 KB
/
10.17.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
static volatile sig_atomic_t sigflag;
static sigset_t newmask, oldmask, zeromask;
static void sig_usr(int), tell_wait(void), tell_parent(pid_t),
wait_parent(void), tell_child(pid_t), wait_child();
int main(void)
{
pid_t pid;
tell_wait();
if ((pid = fork()) < 0) {
printf("fork error\n");
exit(-1);
} else if (0 == pid) {
tell_parent(getppid());
wait_parent();
return 0;
}
tell_child(pid);
wait_child();
return 0;
}
static void sig_usr(int signo)
{
sigflag = 1;
}
static void tell_wait(void)
{
if (signal(SIGUSR1, sig_usr) == SIG_ERR) {
printf("signal(SIGUSR1) error\n");
exit(-1);
}
if (signal(SIGUSR2, sig_usr) == SIG_ERR) {
printf("signal(SIGUSR2) error\n");
exit(-1);
}
sigemptyset(&zeromask);
sigemptyset(&newmask);
sigaddset(&newmask, SIGUSR1);
sigaddset(&newmask, SIGUSR2);
if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) {
printf("SIG_BLOCK error\n");
exit(-1);
}
}
static void tell_parent(pid_t pid)
{
kill(pid, SIGUSR2);
}
static void wait_parent(void)
{
while (0 == sigflag) {
sigsuspend(&zeromask);
}
sigflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) {
printf("SIG_SETMASK error");
exit(-1);
}
}
static void tell_child(pid_t pid)
{
kill(pid, SIGUSR1);
}
static void wait_child(void)
{
while (0 == sigflag) {
sigsuspend(&zeromask);
}
sigflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) {
printf("SIG_SETMASK error");
exit(-1);
}
}