LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   preventing deletion of an opened file (https://www.linuxquestions.org/questions/programming-9/preventing-deletion-of-an-opened-file-525694/)

sayarsoft 02-05-2007 03:40 AM

preventing deletion of an opened file
 
Hi everybody,

Is it possible to prevent a file from deletion, if that file is opened by a process ?

All operations are performed by "root".

rw------- foo.bin

processA opened "foo.bin"

I want "rm foo.bin" can not delete this file.

The only way mandatory locking ?

TIA

matthewg42 02-05-2007 03:59 AM

If you're worried about the program failing because the blocks on disk might get removed while it's running, don't. On unix-like systems file data is only purged from disk when the link count reaches 0. Having a file in a directory raises the link count by one. So does having an open file handle for that file. While the program is running, even if the file is removed from the directory where it exists, the link count will still not drop to 0 because there is an open file handle for that file. Only when the program finishes and the file handle to the file is closed will the data be removed from the disk.

If you simply want to stop people removing the file from the directory, just change the permissions:
Code:

chmod a-w foo.bin
Note that removing a file from a directory actually only requires write permission to the directory in which it lives, but AFAIK, most programs will refuse to remove a file with no write permission, or at least warn you about it:
Code:

matthew@chubby:~/tmp$ touch testfile
matthew@chubby:~/tmp$ chmod a-w testfile
matthew@chubby:~/tmp$ ls -l testfile
-r--r--r-- 1 matthew matthew 0 2007-02-05 09:54 testfile
matthew@chubby:~/tmp$ rm testfile
rm: remove write-protected regular empty file `testfile'? n

...although note that the -f (force) option stops this warning:
Code:

matthew@chubby:~/tmp$ rm -f testfile
matthew@chubby:~/tmp$ ls -l testfile
ls: testfile: No such file or directory


sayarsoft 02-05-2007 04:57 AM

In fact, the problem is

processA continuously writes some kind of log to "foo.bin". If you remove file, processA does'nt know it. And write system call does'nt give any error although when you look at /proc/<pid>/fd, the file has (deleted) info near its name. You can use inotify maybe to close/re-open again that file to continue to logging. Or prevent totally the deletion of this log file. Since flock is an advisory lock, it does'nt work.

Thanks

chrism01 02-05-2007 07:05 PM

Try
chattr -i file

Also, if you get the file creator ie logging prog to immediately unlink (delete) the file after opening it, it will be invisible to other cmds (I think).
This is often used to create temp files that can't be interfered with by other processes.


All times are GMT -5. The time now is 01:57 AM.