Altering a hard linked file in one location seems to destroy it in another location

finderterminal

I have a file, myfile.txt, located in folder1. From the terminal I create a hard link to this file in another directory with the command

ln myfile.txt ~/Documents/folder2

The new file appears as expected in folder2. When I examine the inode for each file using ls -i, it gives the same number, as expected. However, if I open the file and modify it in folder1, after saving, if I open the file from folder2 it has no data. Investigating the inode numbers with ls -i, the two files now have different inode numbers. So my question is, why is this happening? Is this the behavior I should be expecting? My understanding was that hard links were truly indistinguishable files, merely alternate names for the same data. Thus I would expect that altering the file after opening in one location wouldn't be any different than had I opened it from the other location. Can anyone explain what is going on here?

In event that it matters, I'm using Mavericks and the default terminal.app.

Some additional information. The described behavior happened when the file was edited with either TeXShop or TextEdit, so I thought it was something at the OS level. However it appears to not happen when I edit the file with Aquamacs.

Best Answer

A friend of mine found the answer for me. Apparently OS X has a function writeToFile:atomically, which causes a copy of the edited file to be made, then, on saving, replacing the original file with the copy. Since the copy exists in a different place in the hard disk, it has a different inode number. So after the save, the opened file points to a new location and the data at the original inode is removed. This causes the other copy of the file to now point to nothing at the original inode location.