10

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

Any code helps, but Perl would be handy.

Jeff Ferland
  • 17,832
  • 7
  • 46
  • 76

2 Answers2

13

Copy from /proc/pid/fd/file descriptor

Use lsof to find the pid and the file descriptor.

moonshadow
  • 86,889
  • 7
  • 82
  • 122
  • 1
    I just ran my own little test, and this does work, but I don't understand why! Those are symlinks to the actual file, and a symlink accesses the file through its filename, does it not? – Thomas Jul 24 '09 at 16:16
  • 1
    You cannot hard link to the entry in /proc, because hard links have to be on the same filesystem (i.e. your link would have to be in /proc). Copying should be fine. – mark4o Jul 24 '09 at 16:36
  • 1
    mark: noted, thanks. Thomas: they're not real symlinks, they just look like them. Google for proc_register_dynamic for more info. – moonshadow Jul 24 '09 at 16:42
  • 5
    This is very useful procedure for recovering the current data (upvoting :) but it does not really answer the question. `cp` copies the content of the deleted file to a new file. It does not link to the original inode. – pabouk - Ukraine stay strong Aug 06 '13 at 13:18
  • @pabouk So, do you think that it actually worked for the asker or not? Was it erroneously accepted? Maybe the asker misunderstood what they were doing. – can-ned_food Mar 29 '17 at 08:12
  • @can-ned_food: I have no idea what the OP really needed but I think we should not guess. We should follow what is written. I think this answer is close enough to be useful for most of the users and this is important here for the long term. --- The new answer by Poulpatine answers the question. – pabouk - Ukraine stay strong Mar 29 '17 at 09:32
  • So far as concerns any peripheral needs for the original question: Although the descriptor cannot be used to make a filename link to the inode, the descriptor can be used in lieu of such link for most other operations, e.g. `truncate` — http://unix.stackexchange.com/q/61820 – – can-ned_food Mar 29 '17 at 10:02
2

on EXT filesystem you can use debugfs command to recreate the link like :

debugfs -w /dev/mapper/vg0-root -R 'link <16> myfile'

Which will create a "file" named myfile and pointing to inode 16.

Poulpatine
  • 95
  • 1
  • 1
  • 6
  • 1
    This answers the question. Thank you! There is just one problem. The `link` command does not increase the inode's reference count. So in fact the file could be lost right after the program closes the file descriptor and the reference count of the inode decreases to zero. Unfortunately I do not know a simple reliable way how to change the inode's reference count. --- Also a complete answer should show how to get the inode number: `stat -L /proc/PID/fd/FILE_DESCRIPTOR` (or `ls -Li`). – pabouk - Ukraine stay strong Mar 29 '17 at 09:24