Mandatory file lock on linux

2020-01-29 08:21发布

On Linux I can dd a file on my hard drive and delete it in Nautilus while the dd is still going on.

Can Linux enforce a mandatory file lock to protect R/W?

3条回答
▲ chillily
2楼-- · 2020-01-29 08:43

You don't need locking. This is not a bug but a choice, your assumptions are wrong.

The file system uses reference counting and it will mark a file as free when all hard links to the file are removed and all file descriptors are closed.

That approach allows safe operations that Windows, for example, doesn't, as delete, move and rename files in use without needing locking or breaking anything.

Your dd operation is going to succeed despite the file removal.

http://en.wikipedia.org/wiki/Reference_counting#Disk_operating_systems

查看更多
在下西门庆
3楼-- · 2020-01-29 08:53

Linux and Unix OS's can enforce file locks, but it does not do so by default becuase of its multiuser design. Try reading the manual pages for flock and fcntl. That might get you started.

查看更多
Melony?
4楼-- · 2020-01-29 08:54

To do mandatory locking on Linux, the filesystem must be mounted with the -o mand option, and you must set g-x,g+s permissions on the file. That is, you must disable group execute, and enable setgid. Once this is performed, all access will either block or error with EAGAIN based on the value of O_NONBLOCK on the file descriptor. But beware: "The implementation of mandatory locking in all known versions of Linux is subject to race conditions which render it unreliable... It is therefore inadvisable to rely on mandatory locking." See fcntl(2).

查看更多
登录 后发表回答