File Locking
When a file can be accessed by more than one process, a synchronization problem occurs. What happens if two processes try to write in the same file location? Or again, what happens if a process reads from a file location while another process is writing into it?
In traditional Unix systems, concurrent accesses to the same file location produce unpredictable results. However, Unix systems provide a mechanism that allows the processes to lock a file region so that concurrent accesses may be easily avoided.
The POSIX standard requires a file-locking mechanism based on the
fcntl( ) system call. It is possible to lock an
arbitrary region of a file (even a single byte) or to lock the whole
file (including data appended in the future). Since a process can
choose to lock just a part of a file, it can also hold multiple locks
on different parts of the file.
This kind of lock does not keep out another process that is ignorant of locking. Like a critical region in code, the lock is considered “advisory” because it doesn’t work unless other processes cooperate in checking the existence of a lock before accessing the file. Therefore, POSIX’s locks are known as advisory locks .
Traditional BSD variants implement advisory locking through the
flock( ) system call. This call does not allow a
process to lock a file region, just the whole file.
Traditional System V variants provide the lockf( )
function, which is just an interface to fcntl( ). More importantly, System V Release 3 introduced ...