5

I need to lock a file in unix/linux OS. I have googled and read about java.nio.channels Filelock and Reentrant File Lock . But both works in Windows but not in unix. Is there any other way of implementing a lock on file in unix? Any sample code would be highly appreciated.

Thanks, Vignesh

Ankur Lathi
  • 7,636
  • 5
  • 37
  • 49
  • is there any way to do a file lock other than java.nio.channels filelock? –  Feb 20 '14 at 06:34
  • As per this link `Unix locks are ADVISORY`. http://stackoverflow.com/questions/1040828/how-do-i-use-the-linux-flock-command-to-prevent-another-root-process-from-deleti – Subir Kumar Sao Feb 20 '14 at 06:37
  • Could you explain more about the requirement. What kind of lock you want. Do you want to prevent your file from being deleted or do you want to lock your file so no other process can write/read it? – aryann Feb 20 '14 at 06:54
  • i need a lock that can prevent other process from read write operation –  Feb 20 '14 at 07:05
  • 1
    There is no such thing; locks are _advisory_. If the other process does not cooperate by using the same locking primitives/methods as your process does, it can access the file all it wants and there is nothing you can do about this. – fge Feb 20 '14 at 07:21
  • "but not in unix[sic]" this statement is false. – Raedwald May 09 '14 at 10:38

1 Answers1

2

you could have a look at this (not java related) post - https://unix.stackexchange.com/questions/20104/is-there-any-way-to-prevent-deletion-of-certain-files-from-user-owned-directory.

it contains 2 solutions - either chowning the file by root and setting the sticky bit or using ext2/3/4 specific attributes.

both of these solutions are doable from java using System.exec()

Community
  • 1
  • 1
radai
  • 23,949
  • 10
  • 71
  • 115