I. Overview Linux provides multiple features to implement file locking. The simplest method is to create a lock file through atomic operations. The so-called atomic operation is
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 # I nclude # I nclude # I nclude # I nclude 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 % dn ", save_errno );} else {printf ("Open succeededn");} exit (EXIT_SUCCESS );}
First running program: $ lock
Output: Open succeeded
Run the program again: $ lock
Output: Open failed with error is 17
Analysis:When you run the program for the first time, because the file does not exist, the execution is successful. for subsequent execution, the execution fails because the file already exists. if you want the program to run successfully again, you must delete the lock file.
In Linux, error number 17 usually indicates EEXIST, which indicates that a file already exists and the error number is defined in the header file errno. h or (more commonly) it contains the header file.