关于Linux下的强制锁

来源:互联网 发布:广州龙族网络 编辑:程序博客网 时间:2024/05/17 08:21

问:
我在程序中,open一个文件,然后用fcntl()上锁,上锁(是写锁)也是成功的。
但我试图再次打开这个文件时,还是能open。我想要的结果是:再次open时,应该是错误的,请问怎么能办到?

答:
it's advisory lock
when using advisory lock
it is up to programmer to ensure that
whenever access a file or part of that file, acquire its lock first

maybe you need mandantory lock
see the following table

Type of             Blocking        Nonblockingexisting lock       descriptor,     descriptor,on region           tries to        tries toheld by otherprocess             read    write   read    writeread lock           OK      blocks  OK      EAGAINwrite lock          blocks  blocks  EAGAIN  EAGAIN



see /usr/src/linux/Documentation/mandatory.txt and relevant chapters in APUE

the steps you need to take are as follows:

chmod g+s file
chmod g-x file

then remount the filesystem which "file" resides with a "mand" option, e.g.

mount -o remount,mand /dev/hda2 /

there you go!

-------------------------------补充:

1. 强制锁并不会影响文件是否可以被打开

2. 强制锁并未包含在 posix 标准当中。linux (2.0.x)也支持强制性锁,但为了打开这个功能,你必须:

1、对要加锁的文件执行 chmod g+s; chmod g-x (Sys V 强制锁)
2、该文件所在的文件系统在 mount 的时候,加选项: mand

这样,当一个进程用 fcntl 或者 lockf 对一个文件加了写锁之后,其他进程读写这个文件会被 BLOCK,除非 open 加参数 O_NONBLOCK。用 fcntl + F_GETLK,可以得到 BLOCK 本进程的进程号。



原创粉丝点击