Symbolic-Link – Difference Between Symbolic Link and Hard Link After Unlink

symbolic-link

1.

#include <stdio.h>
#include <unistd.h>

void main(){
    link("foo", "bar");
    unlink("foo");
    if(open("bar", 1) < 0)
        printf("open error\n");
    else
        printf("open succeeded\n");
}

2.

#include <stdio.h>
#include <unistd.h>

void main(){
    symlink("foo", "bar");
    unlink("foo");
    if(open("bar", 1) < 0)
        printf("open error\n");
    else
        printf("open succeeded\n");
}

the result from first code is "open succeeded".
and the file "foo" is deleted. only remains "bar" whose contents is same with the file "foo".

the reslut frome second code is "open error". and also only remains "bar".

why these results are generated?
1. especially, although each the hardlink and the symbolic link("bar") points the file "foo", the file "foo" was deleted.
2. why "bar" is not deletd, after unlink("foo"). unlink function means that it removes the link, which points the specified file.(this case, "foo")
3. why result from first code and second code is different?

Best Answer

I'll make a quick reference from an existing article,

With hardlink files,

When deleting files, the data part isn't disposed of until all the filename parts have been deleted. There's a count in the inode that indicates how many filenames point to this file, and that count is decremented by 1 each time one of those filenames is deleted. When the count makes it to zero, the inode and its associated data are deleted.

Please read The difference between hard and soft links for details.

Like, you may be interested in this other factoid on hardlinks,

the count also reflects how many times the file has been opened without being closed (in other words, how many references to the file are still active). This has some ramifications which aren't obvious at first: you can delete a file so that no "filename" part points to the inode, without releasing the space for the data part of the file, because the file is still open.

You could try that with your test-code.

btw: can you recheck your two cases?
I think you would get error for the symlink() case and success for the link() case.
I suggest you run them in different directories or use different file names for the two cases :-)

Related Question