How does the ls command find the hard link count?

后端 未结 2 1052
情歌与酒
情歌与酒 2021-01-27 09:21

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

相关标签:
2条回答
  • 2021-01-27 09:41

    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)

    0 讨论(0)
  • 2021-01-27 09:49

    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.

    0 讨论(0)
提交回复
热议问题