Skip to content

Commit 8479784

Browse files
author
Anton Yarkov
committed
How to handle SIGCHLD in multiprocessing.
1 parent 9ab5c43 commit 8479784

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

multithreading/01 - Signals_SIGCHLD.c

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#include <signal.h>
2+
#include <stdio.h>
3+
#include <stdlib.h>
4+
#include <unistd.h>
5+
#include <sys/wait.h>
6+
7+
#define EXIT_FAILURE 1
8+
9+
// To compile:
10+
// gcc -std=gnu99 "01 - Signals_SIGCHLD.c" -o signals_sigchld
11+
12+
// Task:
13+
// Create a program which creates a child process and handles SIGCHLD signal from its childs.
14+
15+
void kill_child_handler(int sig)
16+
{
17+
int status;
18+
pid_t done = waitpid(
19+
-1, // Any child
20+
&status,
21+
0); // Blocked mode.
22+
if (done == -1)
23+
{
24+
printf("No more child processes.\n", done);
25+
}
26+
else
27+
{
28+
short isNormalTermination = WIFEXITED(status);
29+
if (!isNormalTermination ||
30+
// WEXITSTATUS should be used only if normal termination = true.
31+
(isNormalTermination && WEXITSTATUS(status) != 0))
32+
{
33+
printf("Zombie for PID -- %d failed.\n", done);
34+
exit(EXIT_FAILURE);
35+
}
36+
else
37+
{
38+
printf("Zombie for PID -- %d successfully removed.\n", done);
39+
}
40+
}
41+
}
42+
43+
void main()
44+
{
45+
pid_t main_pid = getpid();
46+
47+
printf("Start of process %d\n", main_pid);
48+
49+
// Handle child process killing.
50+
struct sigaction kill_child_signal;
51+
kill_child_signal.sa_handler = kill_child_handler;
52+
sigemptyset(&kill_child_signal.sa_mask);
53+
kill_child_signal.sa_flags = SA_RESTART; // Permanent handler.
54+
55+
if (sigaction(SIGCHLD, &kill_child_signal, 0) == -1)
56+
{
57+
perror("Error of calling sigaction");
58+
exit(EXIT_FAILURE);
59+
}
60+
61+
// Make child.
62+
pid_t child_pid;
63+
if(child_pid = fork())
64+
{
65+
printf("Started child process %d.\n", child_pid);
66+
67+
printf("Parent process works 1 second.\n");
68+
69+
sleep(1);
70+
}
71+
else
72+
{
73+
// Do anything in child.
74+
}
75+
76+
printf("End of process %d\n", getpid());
77+
78+
exit(0);
79+
}

0 commit comments

Comments
 (0)