Linux file lock flock

  • 2020-05-14 05:55:48
  • OfStack

In the process of multiple processes operating on the same file at the same time, it is very easy to cause data confusion in the file, which requires lock operation to ensure the integrity of the data. The lock for file introduced here is called "file lock" -flock.

flock, recommended locks, not mandatory. A process using flock will file lock, the other one process can direct manipulation is locked files, modify the data in the file, the reason is that flock is used to test if the file is locked, for file has been locked, the other one write data process, the kernel will not stop the process of writing, is recommended to lock the kernel processing strategy.

flock has three main types of operations:

LOCK_SH, Shared lock, multiple processes can use the same lock, often used as a read Shared lock; LOCK_EX, exclusive lock, allowed to only one process at a time, often used as a write lock; LOCK_UN, release lock;

When a process USES flock to try to lock a file, if the file has been locked by another process, the process will block until the lock is released. Or when flock is called, LOCK_NB parameter is used. When trying to lock the file, it finds that it has been locked by another service, and an error will be returned, errno error code is EWOULDBLOCK. That is, it provides two modes of operation: blocking and non-blocking.

The service will block and wait until the lock is released:


flock(lockfd,LOCK_EX)

The service will return the error found when the file has been locked:


ret = flock(lockfd,LOCK_EX|LOCK_NB)

ret = -1, errno = EWOULDBLOCK

The flock lock can be released by calling the LOCK_UN parameter, or by turning off fd (the first parameter of flock is fd), which means that flock is automatically released when the process is shut down.

One of the usage scenarios of flock is: check whether the process already exists;


int checkexit(char* pfile)
{
  if (pfile == NULL)
  {  
    return -1; 
  }  
  int lockfd = open(pfile,O_RDWR);
  if (lockfd == -1) 
  {  
    return -2; 
  }  
  int iret = flock(lockfd,LOCK_EX|LOCK_NB);
  if (iret == -1) 
  {  
    return -3; 
  }  

  return 0;
}


Related articles: