Note that placing a lock does not actually prevent other processes from opening the file, reading from it, or writing to it, unless they acquire locks with fcntl as well.
The http://siber.cankaya.edu.tr/SystemsProgramming/cfiles/lock-file.c program in Fig. 8.2 opens a file for writing whose name is provided on the command line, and then places a write lock on it.
Figure 8.2:
Create a Write Lock with fcntl.
|
$ gcc -o lock-file lock-file.c
$ touch /tmp/test-file
$ ./lock-file /tmp/test-file
Now, in another window, try running it again on the same file.
$ ./lock-file /tmp/test-file
opening /tmp/test-file