删除c中可能锁定的文件
我在 Linux 上的 C 中使用 fcntl 锁,并且遇到了一个困境:尝试删除一个可能被其他进程锁定的文件,这些进程也检查 fcntl 锁定机制。处理这个必须删除的文件的首选方法是什么(我应该简单地删除该文件而不考虑可能具有读取器锁的其他进程还是有更好的方法)? 任何帮助将不胜感激。
I am using fcntl locks in C on linux and have a dilemma of trying to delete a file that may possibly be locked from other processes that also check for the fcntl locking mechanism. What would be the preferred way of handling this file which must be deleted, (Should I simply delete the file without regard of other processes that may have reader locks or is there a better way)?
Any help would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 UNIX 系统上,可以在文件仍处于打开状态时取消链接。这样做会减少文件的引用计数,但实际文件及其索引节点会保留下来,直到引用计数变为零。
On UNIX systems, it is possible to unlink a file while it is still open; doing so decrements the reference count on the file, but the actual file and its inode remains around until the reference count goes to zero.
此外,UNIX系统上的锁默认是建议性的,而不是强制的,因此锁定文件并不会阻止它被打开或取消链接,只是阻止再次锁定。
Moreover, locks on UNIX system are advisory by default, not mandatory, so that locking a file does not prevent it from being open or unlinked, just from being locked again.
正如其他人所指出的,即使您持有锁定,也可以自由删除该文件。
现在,请注意:您没有提到为什么进程锁定此文件,但您应该知道,如果您使用该文件进行进程间同步,删除它是向系统引入微妙的竞争条件的好方法,基本上因为没有办法在单个操作中自动创建并锁定文件。
例如,进程 AA 可能会创建该文件,目的是立即锁定该文件以执行其需要执行的任何更新。但是,没有什么可以阻止进程 BB 首先获取文件上的锁,然后删除该文件,从而为进程 AA 留下现在已删除文件的句柄。进程 AA 仍然能够锁定和更新该文件,但这些更新实际上将“丢失”,因为该文件已被删除。
As others have noted, you are free to delete the file even while you hold the lock.
Now, a cautionary note: you didn't mention why processes are locking this file, but you should be aware that if you are using that file for interprocess synchronization, deleting it is a good way to introduce subtle race conditions into your system, basically because there's no way to atomically create AND lock the file in a single operation.
For example, process AA might create the file, with the intention of locking it immediately to do whatever updates it needs to do. However, there's nothing to prevent process BB from grabbing the lock on the file first, then deleting the file, leaving process AA with a handle to the now deleted file. Process AA will still be able to lock and update that file, but those updates will effectively be "lost" because the file's already been deleted.