linux系统编程之struct flock 结构体
该结构是在lock.h文件中定义。
定义一些文件的锁的选项
The flock structure in the /usr/include/sys/flock.hfile, which describes a lock, contains the following fields:
l_typeDescribes the type of lock. If the value of the Commandparameter to the fcntl subroutine isF_SETLK orF_SETLKW, thel_type field indicates the type of lock to be created. Possible values are:
If the value of theCommand parameter to the fcntlsubroutine is F_GETLK, the l_type field describes an existing lock. Possible values are:
These values are defined in theunistd.h file.
l_startDefines the relative offset in bytes, measured from the starting point in thel_whence field.l_lenSpecifies the number of consecutive bytes to be locked.l_sysidContains the ID of the node that already has a lock placed on the area defined by thefcntl subroutine. This field is returned only when the value of theCommand parameter is F_GETLK.l_pidContains the ID of a process that already has a lock placed on the area defined by thefcntl subroutine. This field is returned only when the value of theCommand parameter is F_GETLK.l_vfs
Specifies the file system type of the node identified in the l_sysidfield.
看一下示例吧!
intwaldirlock(Wal *w){ int r; int fd; struct flock lk; char path[PATH_MAX]; r = snprintf(path, PATH_MAX, "%s/lock", w->dir); if (r > PATH_MAX) { twarnx("path too long: %s/lock", w->dir); return 0; } fd = open(path, O_WRONLY|O_CREAT, 0600); if (fd == -1) { twarn("open"); return 0; } lk.l_type = F_WRLCK; lk.l_whence = SEEK_SET; lk.l_start = 0; lk.l_len = 0; r = fcntl(fd, F_SETLK, &lk); if (r) { twarn("fcntl"); return 0; } // intentionally leak fd, since we never want to close it // and we'll never need it again return 1;}
struct flock 作为fcntl函数的第三个参数,使用F_SETLK,设置了其参数。
更多文章,欢迎访问:http://blog.csdn.net/wallwind