在上面的代码中,"_lock.l_type = F_RDLCK;"表示给文件上读共享锁,"_lock.l_whence = SEEK_SET;"表示从文件开头开始加锁,"_lock.l_start = 0;"表示偏移l_whence多少字节开始加锁,"_lock.l_len = 0;"表示加锁的字节数,即长度(Specifying 0 for l_len has the specialmeaning: lock all bytes starting at the location specified by l_whenceand l_start through to the end of file, no matter how large the filegrows.)。
在上面的代码中,分别编译为slock、glock。先运行slock再运行glock:
代码如下:
To make use of mandatory locks, mandatory locking must be enabled bothon the filesystem that contains the file to be locked, and on the fileitself. Mandatory locking is enabled on a filesystem using the "-o
mand" option to mount(8), or the MS_MANDLOCK flag for mount(2). Mandatory locking is enabled on a file by disabling group execute permission
on the file and enabling the set-group-ID permission bit (see chmod(1)and chmod(2)).
这是说,要实现强制性锁则须将文件所在的文件系统用"-omand"参数来挂载,并且使用chmod函数将文件用户组的x权限去掉。然后用上面同样的代码就可以了。我第一次见这么奇特的函数,实现一个功能并不是通过本身的参数控制,而是系统设置.....幸好我也不用强制性锁。
以上是fcntl加文件锁的简单例子。需要注意的是不同系统的实现并不一样,宏定义也不一样。如:
http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/sys/fcntl.h
/* record locking flags (F_GETLK, F_SETLK, F_SETLKW) */
#define F_RDLCK 1 /* shared or read lock */
#define F_UNLCK 2 /* unlock */
#define F_WRLCK 3 /* exclusive or write lock */
而在debian中,/usr/include/bits/fcntl.h
/* For posix fcntl() and `l_type' field of a `struct flock' for lockf(). */
#define F_RDLCK 0 /* Read lock. */
#define F_WRLCK 1 /* Write lock. */
#define F_UNLCK 2 /* Remove lock. */