17
17
// This program imitates work of 3 processes (parent and 2 childs) with some file with flock-blocking, which means
18
18
// that 2 processes cannot both write into file, but can both read file in the same time. However it cannot write and read in the same time.
19
19
20
+ void kill_child_handler (int sig )
21
+ {
22
+ int status ;
23
+ pid_t done = waitpid (-1 , // Any child
24
+ & status ,
25
+ 0 ); // Blocked mode.
26
+ if (done == -1 )
27
+ {
28
+ printf ("No more child processes.\n" );
29
+ }
30
+ else
31
+ {
32
+ short isNormalTermination = WIFEXITED (status );
33
+ if (!isNormalTermination ||
34
+ // WEXITSTATUS should be used only if normal termination = true.
35
+ (isNormalTermination && WEXITSTATUS (status ) != 0 ))
36
+ {
37
+ printf ("Zombie for PID -- %d failed.\n" , done );
38
+ exit (EXIT_FAILURE );
39
+ }
40
+ else
41
+ {
42
+ printf ("Zombie for PID -- %d successfully removed.\n" , done );
43
+ }
44
+ }
45
+ }
46
+
20
47
int lock_write ()
21
48
{
22
49
int fd ;
@@ -61,12 +88,24 @@ int lock_read(pid_t pid)
61
88
return 1 ;
62
89
}
63
90
64
- void main ()
91
+ int main ()
65
92
{
66
93
pid_t main_pid = getpid ();
67
94
68
95
printf ("Start of process %d\n" , main_pid );
69
96
97
+ // Handle child process killing.
98
+ struct sigaction kill_child_signal ;
99
+ kill_child_signal .sa_handler = kill_child_handler ;
100
+ sigemptyset (& kill_child_signal .sa_mask );
101
+ kill_child_signal .sa_flags = SA_RESTART ; // Permanent handler.
102
+
103
+ if (sigaction (SIGCHLD , & kill_child_signal , 0 ) == -1 )
104
+ {
105
+ perror ("Error of calling sigaction" );
106
+ exit (EXIT_FAILURE );
107
+ }
108
+
70
109
// Lock file for writing.
71
110
if (lock_write ())
72
111
{
@@ -89,12 +128,11 @@ void main()
89
128
if ((next_child_pid = fork ()) > 0 )
90
129
{
91
130
printf ("Start of child process %d.\n" , next_child_pid );
92
-
93
131
printf ("Parent process %d sleeps 5 seconds.\n" , getpid ());
94
132
sleep (5 );
95
133
}
96
134
}
97
-
135
+
98
136
printf ("Process %d tries to access the file...\n" , getpid ());
99
137
100
138
int canread = 0 ;
0 commit comments