Linux – How to Link to a Specific Inode Using lsof

inodelinuxlsof

I have a file that was deleted, but is still held open by a program. I found the inode number using lsof. How can I create a hard link back to that inode?

Best Answer

You can't create a link to it, but you can get it back. Let's do an experiment:

$ echo blurfl >myfile.txt
$ tail -f myfile.txt &
$ rm myfile.txt

myfile.txt is now gone, but the inode is kept alive by the tail command. To get your file back, first find the PID of the process keeping the inode:

$ ps auxw | grep tail
sunny      409  0.0  0.0   8532   824 pts/5    S    18:07   0:00 tail -f myfile.txt

The PID is 409. chdir to /proc/409/fd/ and list the contents:

dr-x------ 2 sunny sunny  0 2009-07-24 18:07:18 .
dr-xr-xr-x 7 sunny sunny  0 2009-07-24 18:07:17 ..
lrwx------ 1 sunny sunny 64 2009-07-24 18:07:33 0 -> /dev/pts/5
lrwx------ 1 sunny sunny 64 2009-07-24 18:07:33 1 -> /dev/pts/5
lrwx------ 1 sunny sunny 64 2009-07-24 18:07:18 2 -> /dev/pts/5
lr-x------ 1 sunny sunny 64 2009-07-24 18:07:33 3 -> /home/sunny/tmp/myfile.txt (deleted)

The /proc/[PID]/fd/ directories contain symlinks to file descriptors of all files the process uses. In this case the symlink "3" points to the deleted file. So, to restore the file, copy the contents to a new file:

$ cat 3 >/home/mydir/saved_file.txt