How to recover a deleted file that is still being used by a process
First: Use a file. In this case I simply run tail -f
(follow) on a one line script called prompt.sh
.
Then background the process CTRL-Z
.
Now delete the file and list the open files belonging to tail: lsof -c tail
.
Notice that the PID
(Process ID) is 4826
and the FD
(File Descriptor) is 3r
.
The 3
is the kernel auto-incrementing the FD number and the r
is for read mode.
Interestingly the kernel starts from 3
because you’ll notice 0-2
are taken.
0u /dev/pts/0 # standard in
1u /dev/pts/0 # standard out
2u /dev/pts/0 # standard error
Available modes to open a file:
r = read access
w = write access
u = read and write access
space if mode unknown and no lock character follows
`-’ if mode unknown and lock character follows
And now we can see that the file descriptor is still there but (deleted)
.
Now that you know which file descriptor it is you can simply make a copy. Either putting it back as the original file name or something different.