|
| 1 | +#include <fcntl.h> |
| 2 | +#include <signal.h> |
| 3 | +#include <stdio.h> |
| 4 | +#include <stdlib.h> |
| 5 | +#include <string.h> |
| 6 | +#include <unistd.h> |
| 7 | +#include <sys/types.h> |
| 8 | +#include <sys/stat.h> |
| 9 | + |
| 10 | +#include "Common.h" |
| 11 | + |
| 12 | +// Compilation: |
| 13 | +// gcc "02 - Lock_via_file.c" -o lockviafile |
| 14 | + |
| 15 | +// This program imitates work of 2 processes (parent and child) with some external resource. |
| 16 | +// To access to resource both processes checks existance of a file, which means resource is still locked. |
| 17 | +// If file is not exists anymore, then this means resource is free. |
| 18 | + |
| 19 | +void handle_child_finishing() |
| 20 | +{ |
| 21 | + // Handle child process killing. |
| 22 | + struct sigaction kill_child_signal; |
| 23 | + kill_child_signal.sa_handler = kill_child_handler; |
| 24 | + sigemptyset(&kill_child_signal.sa_mask); |
| 25 | + kill_child_signal.sa_flags = SA_RESTART; // Permanent handler. |
| 26 | + |
| 27 | + if (sigaction(SIGCHLD, &kill_child_signal, 0) == -1) |
| 28 | + { |
| 29 | + perror("Error of calling sigaction"); |
| 30 | + exit(EXIT_FAILURE); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +int unlock() |
| 35 | +{ |
| 36 | + unlink("/tmp/file.txt"); |
| 37 | + return 1; |
| 38 | +} |
| 39 | + |
| 40 | +int lock() |
| 41 | +{ |
| 42 | + int fd; |
| 43 | + if ((fd = open("/tmp/file.txt", O_WRONLY | // Write to file |
| 44 | + O_CREAT | // Create file if not exists or no block |
| 45 | + O_EXCL, // Return error if file exists, but do not create one |
| 46 | + 0)) == -1) |
| 47 | + { |
| 48 | + return 0; |
| 49 | + } |
| 50 | + |
| 51 | + close(fd); |
| 52 | + |
| 53 | + return 1; |
| 54 | +} |
| 55 | + |
| 56 | +void main() |
| 57 | +{ |
| 58 | + pid_t main_pid = getpid(); |
| 59 | + |
| 60 | + printf("Start of process %d\n", main_pid); |
| 61 | + |
| 62 | + // Handle killing child process. |
| 63 | + handle_child_finishing(); |
| 64 | + |
| 65 | + // Make childs. |
| 66 | + pid_t child_pid; |
| 67 | + if(child_pid = fork()) |
| 68 | + { |
| 69 | + printf("Start of child process %d.\n", child_pid); |
| 70 | + |
| 71 | + sleep(1); |
| 72 | + } |
| 73 | + |
| 74 | + printf("Process %d tries to access the file...\n", getpid()); |
| 75 | + |
| 76 | + int canread = 0; |
| 77 | + while(!canread) |
| 78 | + { |
| 79 | + canread = lock(); |
| 80 | + |
| 81 | + if (canread) |
| 82 | + { |
| 83 | + printf("Process %d accessed the file and working with resource.\n", getpid()); |
| 84 | + sleep(1); |
| 85 | + unlock(); |
| 86 | + printf("File closed and unlocked by process %d.\n", getpid()); |
| 87 | + } |
| 88 | + else |
| 89 | + { |
| 90 | + printf("Wait lock %d.\n", getpid()); |
| 91 | + sleep(1); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + printf("End of process %d\n", getpid()); |
| 96 | + |
| 97 | + exit(0); |
| 98 | +} |
0 commit comments