mutual exclusion between processes, We can let these processes share a memory area (MMAP implementation) and then use some type of synchronization variable in that shared memory area
However, fcntl record locks are often easier to use.
#include <unistd.h>#include<fcntl.h>intFcntl (intFdintCmd.../*struct Flock *arg*/ );structFlock {... ShortL_type;/*Type of Lock:f_rdlck, F_wrlck, F_unlck*/ ShortL_whence;/*How to interpret L_start:seek_set, seek_cur, Seek_end*/off_t L_start; /*starting offset for lock*/off_t L_len; /*Number of bytes to lock*/pid_t L_pid; /*PID of Process blocking our lock (F_GETLK only)*/ ...};
The cmd parameter values are as follows:
Note: 1. The record lock function should not function with standard I/O library functions because these library functions use internal buffering. system calls such as Read,write should be used in conjunction with a record lock operation on a file .
2. File locks cannot be inherited by Fork . For a given process that opens a file, when it closes all the descriptor of the file or it terminates itself, all locks with that file are deleted. The key to deleting a lock is the process ID ( Strcut flock in the L_pid field). Since locks are closely related to process IDs, it is logical that locks cannot be inherited by fork because the parent-child process has a different ID.
Linux IPC Sync (iii): Record lock