如何使用 lstat() 来确定硬 link 与否

how to use lstat() to determine if hard link or not

我的 OS 是 linux。我用 C 编程。我知道我可以使用 lstat() 来识别软 link,即使用 S_ISLNK(st.st_mode)。但是如何识别link是hardlink呢?如果 link 是硬 link,它将被认为是常规文件。不过,我也想区分一下普通文件和硬文件link。有什么办法可以处理这种情况吗?

But how can I recognize the link is hard link?

你不能。

A "hard link" 其实没什么特别的。它只是一个目录条目,恰好指向磁盘上与其他地方的目录条目相同的数据。 only 可靠识别硬链接的方法是将文件系统上的 all 路径映射到 inode,然后查看哪些指向相同的值.

struct stat 有 st_nlink 个硬链接数成员。它 > 1,文件在指向实际文件内容的硬链接之一中说明。

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* protection */
    nlink_t   st_nlink;   /* number of hard links */
    uid_t     st_uid;     /* user ID of owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* total size, in bytes */
    blksize_t st_blksize; /* blocksize for file system I/O */
    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};

示例程序如下:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
    struct stat buf = {0};
    lstat("origfile", &buf);
    printf("number of hard links for origfile: %d\n", buf.st_nlink);
}

输出:

$ touch origfile
$ ./a.out
number of hard links for origfile: 1
$ ln origfile hardlink1
$ ./a.out
number of hard links for origfile: 2
$ ln origfile hardlink2
$ ./a.out
number of hard links for origfile: 3