Pergunta

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?

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top