Deepanshu Pahuja
Deepanshu Pahuja

Reputation: 61

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

I could achieve the same on windows by preserving file handles while on Unix rm does not honour the lock on the files. I even tried Filechannel.lock() but it did not help either.

Any suggestions are appreciated.

Upvotes: 6

Views: 3367

Answers (3)

Stephen C
Stephen C

Reputation: 718788

There is no pure Java solution to this. 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.

(The Linux syscall for locking a file is flock, but flock-style locks are discretionary. Any application that doesn't bother to flock a file won't respect any discretionary locks places on the file by other applications.)

The best you can do is to use chattr +i to set the "immutable" attribute on the file. Unfortunately, that has other effects:

  • The immutable file cannot be written to by any application. It cannot be linked to either.

  • If your application crashes without unsetting the attribute, users are left with files that they mysteriously cannot change or delete. Not even with sudo rm ....

Upvotes: 2

Andrew White
Andrew White

Reputation: 53496

You could also look into chattr which can be used to lock the file.

chattr +i filename

Should render the file undeletable. You can then make it deleteable again via...

chattr -i filename 

Upvotes: 5

Peter Lawrey
Peter Lawrey

Reputation: 533492

As long as you have the handle open, they can remove the file from a directory, but they can't delete the file. i.e. 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.

That is because it's the directory, not the file that is being altered. e.g. if they have write access to the file but not the directory they cannot delete it.

Upvotes: 6

Related Questions