I. Overview
Linux provides multiple features for file locking. The simplest method is to create a lock file through atomic operations. The so-called "atomic operation" means that when a lock file is created, the system will not allow anything else to happen. This provides a way for the program to ensure that the file it creates is unique, and the file cannot be created by other programs at the same time.
Ii. Method
Lock files act only as indicators and must be used by applications through mutual collaboration. The lock file only creates a lock, and the opposite is a mandatory lock.
To create a file used as an indicator, we use an open system call with the O_CREATE and O_EXCL labels. This will allow us to complete two tasks at the same time with an atomic operation: determine that the file does not exist, and then create it.
Iii. Implementation
//file : lock.c#i nclude <unistd.h>#i nclude <stdlib.h>#i nclude <stdio.h>#i nclude <fcntl.h>#i nclude <errno.h>int main(){int file_desc;int save_errno;file_desc = open("/tmp/LockFile.test", O_RDWR | O_CREAT | O_EXCL, 0444);if (file_desc < 0){save_errno = errno;printf("Open failed with error is %d", save_errno);}else {printf("Open succeeded");}exit(EXIT_SUCCESS);}
|
Run the program for the first time:
$ Lock
The output is as follows:
Open succeeded
Run the program again:
$ Lock
The output is as follows:
Open failed with error is 17
Analysis:
When the program is run for the first time, the execution is successful because the file does not exist. Subsequent execution fails because the file already exists. If you want the program to run successfully again, you must delete the lock file.
In Linux, the error number 17 usually indicates EEXIST, which indicates that a file already exists. The error code is defined in the header file errno. h or (more commonly) the header file it contains.