How does the command ls -l
count the number of hard links of an inode?
Does it use the Linux API or is it code that requires deeper knowledge of the Linux kernel so
Here is a real simple program illustrating the user of stat()
to find hard-link counts:
#include <stdio.h>
#include <sys/stat.h>
int main ( int argc, char ** argv ) {
int i;
struct stat st; /* stat puts info here */
for (i = 1; i < argc; ++i) {
if (stat(argv[i], &st) == -1) perror(argv[i]);
else printf("%s has %d hard links\n", argv[i], st.st_nlink);
}
return 0;
}
(Pass it one or more file-names on the command line)
It calls stat to get information about the file (in a struct stat
). Then it looks at the st_nlink
field of the struct stat
.