Monday, April 13, 2015

files removed on last close?

To quote unlink(2):
When the file's link count becomes 0 and no process has the file open, the space occupied by the file shall be freed and the file shall no longer be accessible. If one or more processes have the file open when the last link is removed, the link shall be removed before unlink() returns, but the removal of the file contents shall be postponed until all references to the file are closed.
If having the file open would be interpreted as having a file descriptor, this would match the most common understanding of the issue.

As usual, this is not entirely correct. As far as userspace goes in holding off file removal for an extended period of time, the other thing to look at are memory mappings.

So in an effort to not make this post a three-liner + stolen quite, let's have a look at relevant mappings in a simple program which just sleeps:
00400000-00401000 r-xp 00000000 fd:03 2100640                           /tmp/a.out
00600000-00601000 r--p 00000000 fd:03 2100640                            /tmp/a.out
00601000-00602000 rw-p 00001000 fd:03 2100640                            /tmp/a.out
3685e00000-3685e21000 r-xp 00000000 fd:02 133994                         /usr/lib64/ld-2.17.so
3686020000-3686021000 r--p 00020000 fd:02 133994                         /usr/lib64/ld-2.17.so
3686021000-3686022000 rw-p 00021000 fd:02 133994                         /usr/lib64/ld-2.17.so
Both of these files are in use, but surely it does not have a file descriptor to either one:
lrwx------. 1 meh meh 64 Apr 13 20:58 0 -> /dev/pts/11
lrwx------. 1 meh meh 64 Apr 13 20:58 1 -> /dev/pts/11
lrwx------. 1 meh meh 64 Apr 13 20:58 2 -> /dev/pts/11
 ld-2.17.so does not look like a good candidate for unlink test, so we will focus on /tmp/a.out.
$ stat -L -c '%i' /proc/$(pgrep a.out)/exe
3337221
$ rm /tmp/a.out
$ stat -L -c '%i' /proc/$(pgrep a.out)/exe
3337221
 Which I hope is sufficient for you to believe that the file was not removed just yet because of it being mapped.

No comments:

Post a Comment