-
Notifications
You must be signed in to change notification settings - Fork 1
/
026_parent_child_kill.c
55 lines (47 loc) · 1.01 KB
/
026_parent_child_kill.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
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <math.h>
#include <sys/wait.h>
#include <unistd.h>
//
void sighup_handler(int sig) {
printf("Child process received SIGHUP signal\n");
}
void sigint_handler(int sig) {
printf("Child process received SIGINT signal\n");
}
void sigquit_handler(int sig) {
printf("My Papa has Killed me!!!\n");
exit(0);
}
int main() {
int pid = fork();
if (pid == 0) { // Child process
// Set signal handlers
signal(SIGHUP, sighup_handler);
signal(SIGINT, sigint_handler);
signal(SIGQUIT, sigquit_handler);
// Infinite loop
while (1) {
sleep(1);
}
} else if (pid > 0) { // Parent process
for (int i = 0; i < 5; i++) {
sleep(3);
// Send SIGHUP or SIGINT randomly
if (rand() % 2 == 0) {
kill(pid, SIGHUP);
} else {
kill(pid, SIGINT);
}
}
sleep(3);
kill(pid, SIGQUIT);
wait(NULL);
} else { // Fork error
perror("Fork error");
return 1;
}
return 0;
}