LinuxAnswers - the LQ Linux tutorial section.
Go Back > Blogs > Bits and Pixels
User Name


Concerning free software, programming, and whatever else I find interesting. Also the blog for my Web site,
Rate this Entry

Keep a "secret" file open

Posted 02-05-2012 at 11:13 PM by hydraMax

There is an interesting thing about the way file deletion works in POSIX systems like Linux: When you call a command like "rm" on a file, ultimately you are calling the unlink() function on that file. the unlink() function does indeed remove the file name from the file system; however, the actual file itself is not removed from the file system until the last open file descriptor to that file is closed. (see UNLINK(2))

This means that, effectively, you can keep any file you wish alive, so long as you can keep an open file descriptor pointed at it. (Accessible, at least, to your own user.) For example, do the following:

$ echo "you'll never get me, coppa" >> anonymous
$ tail -f anonymous
you'll never get me, coppa
Now, in another shell (in the same directory):

$ rm anonymous 
$ ls anonymous
ls: cannot access anonymous: No such file or directory
The file is gone, or so it seems...

$ ps -e | grep tail
 9868 pts/0    00:00:00 tail
$ cd /proc/9868/fd
$ ls -lh
total 0
lrwx------ 1 cmhoward cmhoward 64 Feb  5 19:57 0 -> /dev/pts/0
lrwx------ 1 cmhoward cmhoward 64 Feb  5 19:57 1 -> /dev/pts/0
lrwx------ 1 cmhoward cmhoward 64 Feb  5 19:56 2 -> /dev/pts/0
lr-x------ 1 cmhoward cmhoward 64 Feb  5 19:57 3 -> /scratch/cmhoward/anonymous (deleted)
lr-x------ 1 cmhoward cmhoward 64 Feb  5 19:57 4 -> anon_inode:inotify
$ echo "nobody knows the trouble I've seen..." >> 3
$ tail -f 3
you'll never get me, coppa
nobody knows the trouble I've seen...
(The actually process number will differ, of course.)

If you go back to the first shell, you will see that our second line of text has been added to first. You can close the first "tail" process, but the file will continue to exist because the second one now has the file open.

If you used C functions in a custom program (instead of tail) and named your processes intelligently, you might be able to keep a very large file open for quite some time, at least until the next system reboot, without anyone noticing. And it wouldn't show up as memory usage (in say, a top printout) which is an added bonus.

That is common knowledge to people who are familiar with the unlink function, of course. But it was rather interesting anyway.
Posted in Uncategorized
Views 467 Comments 0
« Prev     Main     Next »
Total Comments 0




All times are GMT -5. The time now is 05:17 PM.

Main Menu

Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration