歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Linux系統編程之struct flock 結構體

該結構是在lock.h文件中定義。

lock.h File

功能

定義一些文件的鎖的選項

Description

The flock structure in the /usr/include/sys/flock.h file, which describes a lock, contains the following fields:

l_type Describes the type of lock. If the value of the Command parameter to the fcntl subroutine is F_SETLK orF_SETLKW, the l_type field indicates the type of lock to be created. Possible values are:

F_RDLCK
A read lock is requested.
F_WRLCK
A write lock is requested.
F_UNLCK
Unlock. An existing lock is to be removed.

If the value of the Command parameter to the fcntl subroutine is F_GETLK, the l_type field describes an existing lock. Possible values are:

F_RDLCK
A conflicting read lock exists.
F_WRLCK
A conflicting write lock exists.
F_UNLCK
No conflicting lock exists.
l_whence Defines the starting offset. The value of this field indicates the point from which the relative offset, the l_startfield, is measured. Possible values are:
SEEK_SET
The relative offset is measured from the start of the file.
SEEK_CUR
The relative offset is measured from the current position.
SEEK_END
The relative offset is measured from the end of the file.

These values are defined in the unistd.h file.

l_start Defines the relative offset in bytes, measured from the starting point in the l_whence field. l_len Specifies the number of consecutive bytes to be locked. l_sysid Contains the ID of the node that already has a lock placed on the area defined by the fcntl subroutine. This field is returned only when the value of the Command parameter is F_GETLK. l_pid Contains the ID of a process that already has a lock placed on the area defined by the fcntl subroutine. This field is returned only when the value of the Command parameter is F_GETLK.

l_vfs

Specifies the file system type of the node identified in the l_sysid field.

看一下示例吧!

  1. int  
  2. waldirlock(Wal *w)  
  3. {  
  4.     int r;  
  5.     int fd;  
  6.     struct flock lk;  
  7.     char path[PATH_MAX];  
  8.   
  9.     r = snprintf(path, PATH_MAX, "%s/lock", w->dir);  
  10.     if (r > PATH_MAX) {  
  11.         twarnx("path too long: %s/lock", w->dir);  
  12.         return 0;  
  13.     }  
  14.   
  15.     fd = open(path, O_WRONLY|O_CREAT, 0600);  
  16.     if (fd == -1) {  
  17.         twarn("open");  
  18.         return 0;  
  19.     }  
  20.   
  21.     lk.l_type = F_WRLCK;  
  22.     lk.l_whence = SEEK_SET;  
  23.     lk.l_start = 0;  
  24.     lk.l_len = 0;  
  25.     r = fcntl(fd, F_SETLK, &lk);  
  26.     if (r) {  
  27.         twarn("fcntl");  
  28.         return 0;  
  29.     }  
  30.   
  31.     // intentionally leak fd, since we never want to close it   
  32.     // and we'll never need it again   
  33.     return 1;  
  34. }  

struct flock 作為fcntl函數的第三個參數,使用F_SETLK,設置了其參數。

Copyright © Linux教程網 All Rights Reserved