2008-03-28 22:14:54

Insanity for beginners: undeleting open files

If you have accidentally deleted a file which is still open, there is an easy way to undelete it. For this stunt, please make sure that the /proc file system is mounted.

First, we create a file to test with:

$ echo test > testfile
$ sha1 testfile
4e1243bd22c66e76c2ba9eddc1f91394e57f9f83
$

Then we create a process to hold the file open:

$ tail -f testfile &
$ test

Then we delete our test file:

$ rm -f testfile
$

Now we determine the PID of the process which holds our file open:

$ ps waux | grep [t]ail
tonnerre 5962 0.0 0.0 44 616 ttyp8 S+ 10:45PM 0:00.01 tail -f testfile
$

The remaining question is: which file descriptor is the one we're looking for?

$ ls -l /proc/5962/fd
ls: 8: Bad file descriptor
total 2
crw--w---- 1 tonnerre tty 3, 8 Mar 29 22:45 0
crw--w---- 1 tonnerre tty 3, 8 Mar 29 22:45 1
crw--w---- 1 tonnerre tty 3, 8 Mar 29 22:45 2
-rw-r--r-- 1 tonnerre staff 5 Mar 29 22:45 3
lr-xr-xr-x 1 tonnerre staff 0 Mar 29 22:45 4 -> [kqueue]
prw------- 1 root wheel 0 Mar 29 22:45 5
prw------- 1 root wheel 0 Mar 29 22:45 7
$

The only normal file here was 3, so let's get hold of it!

$ ln /proc/5962/fd/3 test
$ sha1 test
4e1243bd22c66e76c2ba9eddc1f91394e57f9f83
$

Congratulations! We got our file back.


Posted by Tonnerre Lombard | Permanent link | File under: programming, general