The method of creating Lock File by linux
This article introduces the relevant knowledge of "the method of creating lock files by linux". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
I. Overview
Linux provides a variety of features for file locking. The easiest way is to create a lock file in an atomic way. The so-called "atomic operation" is that when you create a lock file, the system will not allow anything else to happen. This provides a way for a program to ensure that the file it creates is unique, and that the file cannot be created by other programs at the same time.
2. Methods
Lock files simply act as indicators, and programs need to work with each other to use them. Lock files are only recommended locks, as opposed to mandatory locks.
To create a file to use as an indicator, we use the open system call with the O_CREATE and O_EXCL flags. This allows us to do two things at the same time as an atomic operation: make sure the file doesn't exist, and then create it.
III. Realization
The code is as follows:
/ / 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% d\ n", save_errno)
}
Else {
Printf ("Open succeeded\ n")
}
Exit (EXIT_SUCCESS)
}
Run the program for the first time:
$lock
The output is as follows:
Open succeeded
Let's run the program again:
$lock
The output is as follows:
Open failed with error is 17
Analysis:
The first time you run the program, the execution is successful because the file does not exist. For subsequent execution, failed because the file already exists. If you want the program to execute successfully again, you must delete the lock file.
In Linux systems, the error number 17 usually represents EEXIST, which is used to indicate that a file already exists. The error number is defined in the header file errno.h or (more commonly) the header file it contains.
This is the end of the content of "how to create lock files in linux". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!