Mandatory file lock on linux

怎甘沉沦 提交于 2019-11-26 16:48:09

问题


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?


回答1:


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).




回答2:


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:


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.



来源:https://stackoverflow.com/questions/12062466/mandatory-file-lock-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!