0

I'm writing a program that does something similar to the disk usage utility on Linux, and I'm having trouble when it comes to Hard links.

I currently have the program running, and it determines whether a program has hard links. I use stat() on the file to determine this.

if (st.st_nlink > 1)

When I run this, both the link and the program that it is linked to return, but the disk usage utility would only report the program and not its hard link.

How do I tell the difference between a program and its hard link(s) in Linux using C?

Clark Kent
  • 1,178
  • 1
  • 12
  • 26

1 Answers1

2

First, why do you handle differently program and data files with multiple hard links?

Then, what matters is not the name or their number (notice that hard links add another name to a file), but the inode. For a "file" (i.e. an inode) having more than one hard links, all the names pointing to the same inode are of equal rights (there is no "main" name, all names pointing to that same inode are equivalent).

So after calling the stat(2) syscall you want to use both the st_dev and st_ino fields. Together they uniquely identify a file, that is its inode.

Hence, for files with an st.st_nlink>1 you'll probably add the (st_dev,st_ino) pair to some hashtable or set container.

In C++ you could probably use even some std::set<std::pair<dev_t,ino_t> > but in C you have to make such a container.

NB: a file (e.g. some inode) could even have zero names (e.g. if an unlink(2) syscall has been called after the open(2)), this is how temporary files are made.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Hmm... I'm not getting the expected results using this. Is what I'm really asking is how do I differentiate between a hard link and the file it corresponds to. When I run this, I get both the st_dev and st_ino coming out identical for both the file and hard link for my test cases. When these 2 files pop out, how can I say "This one is the Hard Link" ? – Clark Kent Apr 18 '13 at 12:42
  • The point is that there are no one "main" name and other "slave" names! All hard names are "equal". – Basile Starynkevitch Apr 18 '13 at 12:50
  • So it is impossible to determine which is which? – Clark Kent Apr 18 '13 at 12:52
  • 1
    It is impossible because the question has no sense. All names to the same inode are equivalent, by definition of hard links. – Basile Starynkevitch Apr 18 '13 at 12:53