Skip to content

Commit 7685599

Browse files
optiklaboptiklab
optiklab
authored and
optiklab
committed
Improved/fixed file locking.
1 parent 43fbb9c commit 7685599

File tree

1 file changed

+41
-3
lines changed

1 file changed

+41
-3
lines changed

multithreading/02 - Flock.c

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,33 @@
1717
// This program imitates work of 3 processes (parent and 2 childs) with some file with flock-blocking, which means
1818
// 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.
1919

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+
2047
int lock_write()
2148
{
2249
int fd;
@@ -61,12 +88,24 @@ int lock_read(pid_t pid)
6188
return 1;
6289
}
6390

64-
void main()
91+
int main()
6592
{
6693
pid_t main_pid = getpid();
6794

6895
printf("Start of process %d\n", main_pid);
6996

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+
70109
// Lock file for writing.
71110
if (lock_write())
72111
{
@@ -89,12 +128,11 @@ void main()
89128
if ((next_child_pid = fork()) > 0)
90129
{
91130
printf("Start of child process %d.\n", next_child_pid);
92-
93131
printf("Parent process %d sleeps 5 seconds.\n", getpid());
94132
sleep(5);
95133
}
96134
}
97-
135+
98136
printf("Process %d tries to access the file...\n", getpid());
99137

100138
int canread = 0;

0 commit comments

Comments
 (0)