Linux file Lock __linux

Source: Internet
Author: User
Tags flock function prototype
One, what is the file lock for the word lock, we must not unfamiliar, because there are a lot of locks in our lives, and they all play its part, now the world's lock function can be summed up as a sentence, that is to prevent certain people to do something, for example, the door lock is to prevent people other than the owner into the house, You can't get into the house and you can't use the things in the house.
And because programs often need to share data, and this is usually done through a file, imagine a situation where a process is writing to a file, and another program B needs to read the same file and read the data as it needs to run its own program. Process B may read the garbled data because it does not know that another process A is overwriting the data in this file.
In order to solve a similar problem, there is a file lock, in simple terms, this is a safe way to update a file, and when a program is writing to a file, it goes into a temporary state where another program will automatically stop and wait for the state to end if it tries to read the file. Linux provides a number of features for file locking, the simplest of which is to create a lock file as an atomic operation.
In the case of the previous example, a file lock is when a file is written, blocking other processes that need to be written or read in order to manipulate the file.
Second, create a lock file to create a lock file is very simple, we can use the open system call to create a lock file, when calling open Oflags parameters to increase the parameters o_creat and O_EXCL flags, such as File_desc = Open ("/tmp/ Lck.test ", o_rdwr| O_creat| O_EXCL, 0444); You can create a lock file/tmp/lck.test. O_creat| O_EXCL, you can make sure that the caller can create a file that prevents two programs from creating the same file at the same time, and if the file (/tmp/lck.test) already exists, the open call fails and returns-1.
If a program is executing on it, you just need to monopolize a resource for a short time, which is often called a critical section, and we need to create a lock file using open system calls before entering the critical section, and then delete the lock file with unlink system calls when exiting the critical section.
Note: Lock files only act as an indicator, and programs need to be used in collaboration with each other, which means that locking files is only a recommended lock, not a mandatory lock, and does not actually prevent you from reading and writing data from files.
Take a look at the following example: The source file file name is filelock1.c, the code is as follows: [CPP]  View plain copy print? #include  <unistd.h>   #include  <stdlib.h>   #include  <stdio.h >   #include  <fcntl.h>   #include  <errno.h>      Int main ()    {       const char *lock_file =  "/ Tmp/lck.test1 ";       int n_fd = -1;        int n_tries = 10;          while (n_tries--)         {                    //Create lock file            n_fd =  open (lock_file, o_rdwr| O_creat| o_excl, 0444);           if (n_fd == -1)             {                            //Creation Failure                 printf ("%d - lock already present\n",  getpid ());               sleep (2);            }            else           {                      //Create success                 printf ("%d - i have exclusive access\n",  getpid ());                sleep (1);     &nbsP;         close (N_FD);                             //Delete lock file, release lock                unlink ( Lock_file);               sleep (2);            }       }        return 0;  }   runs two instances of the same program at the same time, and the results are:
From the results of the operation can be seen two of the program cross to lock the file, but the real operation is, each call to the Open function to check the/tmp/ Lck.test1 If the file exists, if an open call fails, the process has locked the file, and if the file does not exist, create the file and display the license information. But this approach has some drawbacks, we can see that the file/tmp/lck.test1 was created many times, but also by the unlink deleted many times, that is, we can not use the data has been in advance of the file as such a lock file, because if the file already exists, the open call will always fail.
The feeling is that it's more like a coordinated arrangement of processes, more like binary semaphores, where files exist as 0, not 1, not real file locks.
Third, area lock we still have one more question, is that if the same file has more than one process to read and write to it, and a file can only be written by one process at a time, but the areas read and written by multiple processes are unrelated, if you always have to wait for a process to write other processes to read and write it, the efficiency is too low, So is it possible for multiple processes to read and write files at the same time to improve the efficiency of data literacy?
To solve the problem mentioned above, and the problem appearing in 2nd, that is, the problem of not locking the file to the specified existing data file, we propose a new solution, that is, Zone locking.
In simple terms, a zone lock is where a part of a file is locked, but other programs can access other parts of the file.
However, the creation and use of zone locks is much more complex than the file locking described above.
1. Create a zone lock on Linux to do this, we can use FCNTL system calls and LOCKF calls, but the following fcntl system is used to explain the creation of zone locks.
FCTNL's function is: int fctnl (int fildes, int command, ...); It operates on an open file description and can complete different tasks based on the command parameter's setup, which has three optional tasks: f_getlk,f_setlk,f_setlkw, the meaning of these three parameters is detailed below. When using these commands, the third parameter of fcntl must be a pointer to the flock structure, so in practice, FCTNL's function prototype is generally: int fctnl (int fildes, int command, struct flock *flock_ ST);
2. Flock Structure
Accurately, the flock structure relies on a specific implementation, but it includes at least the following members: short l_type; file lock type, corresponding to F_rdlck (read lock, also called shared lock), F_unlck (unlock, also known as the Purge Lock), F_wrlck (write lock, Also called the exclusive lock).
Short l_whence from which relative position of the file, corresponding to Seek_set (file header), Seek_cur (current position), Seek_end (end of file).
off_t L_start, starting at the L_start byte starting from l_whence.
off_t L_len The length of the area locked.
pid_t l_pid; Used to record the process in which the parameter holds the lock.
Members L_whence, L_start, and L_len define an area in a file, a contiguous set of bytes, such as: struct flock region; Region.l_whence = Seek_set; Region.l_start = 10; Region.l_len = 20;
This indicates that the area of the FCNTL function operation is locked to 20 bytes between the 10th to 29th byte of the beginning of the file header.
3, the type of file lock from the above flock member L_type value we can know that the type of file locks are mainly three kinds, here to their detailed explanation.
F_rdlck: From its name we can know that it is a read lock, also called shared lock. Many different processes can have read (shared) locks on the same (or overlapping) area of the file. And as long as any process has a read (shared) lock, no process can obtain the write (exclusive) lock on the zone. In order to obtain a shared lock, the file must be opened in either Read or read/write mode.
The simple point is that when a process is reading data in a file, the data in the file can not be changed or rewritten, this is to prevent data from being changed to read the program read the data is garbled, and the same area in the file can be read by several processes simultaneously, which is easy to understand, because reading does not destroy the data, Or the read operation does not change the data of the file.
F_wrlck: From its name, we can know that it is a write lock, also called an exclusive lock. Only one process can have a write (exclusive) lock in any particular area of the file. Once a process has such a lock, no other process can acquire any type of lock on the zone. In order to obtain a write (exclusive) lock, the file must also be opened in either Read or read/write mode.
The simple point is that a file has the same area (or overlapping) area at the same time, only one process can write to it, and other processes cannot read data for the zone during the write operation. This requirement is obvious, because if two processes write to a file at the same time, the contents of the file will be confused, and since the write will change the data in the file, so it does not allow other processes to read and delete file data and other operations.
F_unlck: It can be known from its name that it is used to unlock a locked area.
4, the meaning of the different command when we talked about the command arguments for the FCNTL function, we said three options, which are explained in detail here.
The F_GETLK command, which is used to get lock information on the file opened by Fildes (Fcntl's first argument), does not attempt to lock the file, the calling process can pass the lock type information it wants to create to fcntl, and the function call returns any information that will block the acquisition of the lock, That is, it can test whether the lock you want to create can be created successfully. When the FCNTL call succeeds, it returns non-1, and if the lock request can be executed successfully, the flock structure remains unchanged, and if the lock request is blocked, fcntl overwrites the flock structure with the relevant information. Returns-1 when failed.
So, if the call succeeds, the caller can check the contents of the flock structure to determine if it has been modified to see if the lock request can be executed successfully, and because the L_pid value will be set to the identifier of the process that owns the lock, so in most cases, You can determine whether the flock structure has been modified by examining whether the field has changed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.