Linux: recover a deleted file still open (lsof and /proc)
Recover the contents of a deleted file still held open by a process, using lsof and /proc/<pid>/fd.
On Linux, a deleted file is only really freed from disk once no process holds it open. As long as the process using it keeps running, its contents remain reachable under /proc/<pid>/fd/<descriptor>, and you can copy them from there.
Procedure
-
Locate the deleted file with
lsof, which lists open files:lsof | grep myfileExample output:
less 4158 user 4r REG 3,65 114383 1276722 /home/user/myfile (deleted)The columns give the command name, the PID (
4158) and the file descriptor (4r: descriptor 4, opened for reading). -
Copy the contents from
/proc:cp /proc/4158/fd/4 myfile.savedDo not use
cp -a./proc/<pid>/fd/<descriptor>is a symbolic link to the deleted file, so-awould copy the broken link instead of the data. -
Verify the copy, for example with
cmpif a reference copy exists.
Deleted libraries still in use
After a library is updated, a process may keep using the old version, which is shown as (deleted). The following command lists them:
lsof -n +c 0 2> /dev/null | grep 'DEL.*lib'
Remarks
- Do not let the process exit: once it stops, the file is really gone. For a media file being played, it is better to pause the application immediately.
- The method only works while a process still has the file open.