-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathsignal_fork.c
50 lines (46 loc) · 1.02 KB
/
signal_fork.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
/* https://stackoverflow.com/questions/7696925/how-to-send-a-signal-to-a-process-in-c/50075790#50075790
*
* Some fun with signal sending.
*
* Fork a process, then a signal to it every second.
*
* The fork prints a message to stdtout when the signal is received:
*
* SIGUSR1
* SIGUSR2
* SIGUSR1
* SIGUSR2
* ...
*/
#include "common.h"
void signal_handler(int sig) {
char s1[] = "SIGUSR1\n";
char s2[] = "SIGUSR2\n";
if (sig == SIGUSR1) {
write(STDOUT_FILENO, s1, sizeof(s1));
} else if (sig == SIGUSR2) {
write(STDOUT_FILENO, s2, sizeof(s2));
}
signal(sig, signal_handler);
}
int main(void) {
pid_t pid;
signal(SIGUSR1, signal_handler);
signal(SIGUSR2, signal_handler);
pid = fork();
if (pid == -1) {
perror("fork");
assert(false);
}
if (pid == 0) {
while (1);
exit(EXIT_SUCCESS);
}
while (1) {
kill(pid, SIGUSR1);
sleep(1);
kill(pid, SIGUSR2);
sleep(1);
}
return EXIT_SUCCESS;
}