Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the linux flock command to prevent another root process from deleting a file?

I would like to prevent one of my root processes from deleting a certain file. So I came across the flock command, it seems to fit my need, but I didn't get its syntax.

If I only indicate a shared lock, it doesn't work:

flock -s "./file.xml"

If I add a timeout parameter, it still doesn't work:

flock -s -w5 "./file.xml"

It seems that way, it fits in flock [-sxun][-w #] fd# way. (What is this fd# parameter?)

So, I tried:

flock [-sxon][-w #] file [-c] command

Using flock -s -w5 "./file.xml" -c "tail -3 ./file.xml" and it worked, tail command at ./file.xml was executed.

But I would like to know, does the lock end after the command or does it last 5 seconds after the end of the command execution? My main question is, how can I prevent another root process from deleting a file in linux?

like image 483
Danmaxis Avatar asked Jun 24 '09 20:06

Danmaxis


People also ask

What does Flock command do in Linux?

They lock a specified file or directory, which is created (assuming appropriate permissions) if it does not already exist. By default, if the lock cannot be immediately acquired, flock waits until the lock is available.

Which Linux command is capable of deleting files?

In the Linux operating system, files, directories, and links can be removed using the rm and unlink command, but only empty directories can be deleted using the rmdir command.


1 Answers

No, flock does NOT prevent anyone from doing anything. Unix locks are ADVISORY, which means that they prevent other processes from also calling flock (or in the case of a shared lock, prevent another process using an exclusive one).

It doesn't stop root, or anyone else, from reading, writing or deleting the file.

In any case, even if it was a mandatory lock, it wouldn't stop the file being deleted, as it's the file being locked not the directory entry.

like image 72
MarkR Avatar answered Oct 17 '22 10:10

MarkR