[英]How to prevent user from deleting a file which is being used by JVM
I have a piece of JAVA code which reads a few files and keeps them loaded into memory for sometime. 我有一段JAVA代码,它读取一些文件,并将它们保存到内存中一段时间。 The file handles are preserved after reading.
读取后保留文件句柄。 My problem here is that I want to restrict user from deleting these files using "DEL" key or rm command.
我的问题是我想限制用户使用“DEL”键或rm命令删除这些文件。
I could achieve the same on windows by preserving file handles while on Unix rm does not honour the lock on the files. 我可以通过保留文件句柄在Windows上实现相同的功能,而在Unix上,rm不承认对文件的锁定。 I even tried
Filechannel.lock()
but it did not help either. 我甚至尝试过
Filechannel.lock()
但它也没有帮助。
Any suggestions are appreciated. 任何建议表示赞赏。
As long as you have the handle open, they can remove the file from a directory, but they can't delete the file. 只要您打开句柄,他们就可以从目录中删除该文件,但是他们无法删除该文件。 ie the file isn't removed until you close the file or your process dies.
即,在关闭文件或进程终止之前,文件不会被删除。
I even tried Filechaanel.lock() but it did not help either.
我甚至尝试过Filechaanel.lock(),但它也没有帮助。
That is because it's the directory, not the file that is being altered. 那是因为它是目录,而不是正在改变的文件。 eg if they have write access to the file but not the directory they cannot delete it.
例如,如果他们对文件具有写访问权但对目录没有删除权限。
There is no pure Java solution to this. 没有纯Java解决方案。 In fact, I don't think there is a solution at all that doesn't have potentially nasty consequences.
事实上,我认为没有任何解决方案可能没有潜在的恶劣后果。 The fundamental problem is that UNIX / LINUX doesn't have a way to temporarily place a mandatory lock on a file.
根本问题是UNIX / LINUX无法临时在文件上放置强制锁定。 (The Linux syscall for locking a file is
flock
, but flock-style locks are discretionary. An application that doesn't bother to flock
a file won't be affected by other applications locks on the file.) (用于锁定文件的Linux系统调用是
flock
,但是flock风格的锁是自行决定的。一个不费心去flock
文件的应用程序不会受到文件上其他应用程序锁的影响。)
The best you can do is to use chattr +i
to set the "immutable" attribute on the file. 您可以做的最好的事情是使用
chattr +i
在文件上设置“immutable”属性。 Unfortunately, that has other effects: 不幸的是,这有其他影响:
The immutable file cannot be written to or linked to either. 不可变文件无法写入或链接到任何一个。
If your application crashes without unsetting the attribute, the user is left with a file that he / she mysteriously cannot change or delete. 如果您的应用程序在未取消设置属性的情况下崩溃,则会向用户留下他/她神秘无法更改或删除的文件。 Not even with sudo or su.
甚至没有sudo或su。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.