LLI Wiki — My Digital Knowledge Base

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

  1. Locate the deleted file with lsof, which lists open files:

    lsof | grep myfile
    

    Example 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).

  2. Copy the contents from /proc:

    cp /proc/4158/fd/4 myfile.saved
    

    Do not use cp -a. /proc/<pid>/fd/<descriptor> is a symbolic link to the deleted file, so -a would copy the broken link instead of the data.

  3. Verify the copy, for example with cmp if 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

Mastodon LLIMastodon SocialFosstodon