How to Use the Linux Flock Command to Prevent Another Root Process from Deleting a File

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

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.

flock() doesn't preventing other process to get exclusive lock

Try:

if ((fd1 = open( "file1", O_RDWR | O_CREAT | O_TRUNC)) == -1)
// ^ ^

As what you have written is the same as:

if (open( "file1", O_RDWR | O_CREAT | O_TRUNC) == -1)
fd1 = TRUE;
else
fd1 = FALSE;

Therefore you are attempting to lock stdin or stdout (depending on the result of open()).

flock doesn't get released on logout/reboot

Don't remove the file; just let the process holding the file open exit.

(
if [[ -n $LOGFILE ]]; then
exec >>"$LOGFILE" 2>&1
fi

flock -xn 200 || { show_message "$(basename ${0}): cannot acquire lock ${LOCK_FILE}"; exit 3; }

main
) 200>"${LOCK_FILE}"

When main exists, the subshell that opened $LOCK_FILE will exit as well, and the lock will be dropped.

If you want to release the lock explicitly, use flock --unlock 200 instead of removing the file.

How to protect file from reading by other processes without mandatory lock in Linux?

Well, if you have a sensitive data, then you should decide to whom you can trust. Do remember that you have to trust at least to superuser (well, with SELinux this is not a complete truth but nevertheless).

Then when you decide to whom you can trust, you may configure file permissions and permissions of the directory where it's located such a way that only trusted users are permitted to access its content. Directory permissions are required to hide the fact that the file exists.

You could also delete the file right after it's created and opened and then write to the opened file. This way you can assure that the file is actually removed if your program unexpectedly dies



Related Topics



Leave a reply



Submit