Linux hardlink confusion

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.


Solution 1:

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.