file lock (record lock)

1. The file lock can lock a certain part of the file to be modified, and precisely control it to the byte

Set file lock through fcntl() function

  fcntl(int fd,int cmd,.........);

  Parameters: fd: file descriptor

        cmd:F_GETLK: Test whether the lock can be added (but it may not be able to be added, non-atomic operation. Generally not used)

       F_SETLK: lock the file, then return immediately with an error

       F_SETLKW: lock the file, block if it cannot be added

    The third parameter is a structure of type strcuct flock such as struct folct  lock;

     

1  lock .l_type = F_WRLCK;         // Add a write lock    // F_RDLCK read lock, F_UNLCK release lock 
2  lock .l_whence=SEEK_SET;    // relative head offset      // SEEK_END SEEK_CUR    
3  lock .l_start = 0 ;   // relative Header offset is 0    
 4  // lock.l_start=-5;   // The pointer moves 5 bytes to the left to start 
5  
6  lock.l_len = 5 ;   // The number of bytes to lock
 7  // lock.l_len = 0;   // Everything from start is locked, including newly written ones. (locked throughout)

    fctnl(fd,F_SETLKW,&lock);

  2. Unlock

    lock.l_type=F_UNLCK;

    fcntl(fd,F_SETLKW,&lock);
  Closing the file will release all locks the process has placed on the file.

  Note the implicit release, such as:

    newfd=dup (fd);

    close( newfd //All locks added to the process will still be released
  Reason: record locks are marked with process pid, not file descriptors. Once a close function is detected, five file locks corresponding to the process will be checked. and close.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324969420&siteId=291194637