I am confused with Linux hard link,

I created a hardlink with this command on my Ubuntu box,

ln f1 f2

So f2 should be a hardlink of f1, but why I changed f2 with emacs and saved f2, f1 didn't change at all. My understanding is f1 was supposed to have whatever change I did on f2.

  • Why not use a softlink instead? – Wilshire Jun 18 '11 at 16:26

I did some testing and figured out what happened. First, the command ls -li shows you the inode number in the first column, two hardlinks to the same file will have the same inode number:

$ echo hi > f1
$ ln f1 f2
$ ls -li
total 8
1646595 -rw-r--r-- 2 randy randy 3 2011-06-18 06:50 f1
1646595 -rw-r--r-- 2 randy randy 3 2011-06-18 06:50 f2

Files f1 and f2 both have inode number 1646595, they're hardlinks to the same data. I used emacs to edit f1 and saved:

$ ls -li
total 12
1646597 -rw-r--r-- 1 randy randy 9 2011-06-18 06:51 f1
1646595 -rw-r--r-- 2 randy randy 3 2011-06-18 06:50 f1~
1646595 -rw-r--r-- 2 randy randy 3 2011-06-18 06:50 f2

Now, f1~ and f2 have the same inode number, and f1 has a new inode number.

What emacs did when you saved is renamed f1 to f1~ and created a new file f1. f1~ remained hardlinked to f2, while f1 being a new file isn't linked anywhere else.

I don't know if there's a setting in emacs to change this behavior.

  • 2
    That is often the case that application writing an existing file doesn't directly write to it, but writes to a new one and renames. In fact this is often desirable, as it is safer: the file won't be truncated if something goes wrong (out of disk space, power loss, etc.). Other advantage of this behaviour is that hard links may be used for making 'copy on write' duplicates of files or whole directory trees (the directories are not hard-linked, only the files inside). – Jacek Konieczny Jun 18 '11 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.