2016-11-12 14 views
0

私のOSはLinuxです。私はCでプログラムします。ソフトリンクを認識するためにlstat()を使うことができます。つまり、S_ISLNK(st.st_mode)を使用することができます。しかし、リンクがハードリンクであることを私はどのように認識できますか?リンクがハードリンクの場合、通常のファイルと見なされます。しかし、私はまた、通常のファイルとハードリンクを区別したい。このケースを処理する方法はありますか?ハードリンクかどうかを判断するためにlstat()を使用する方法

+0

確かにそれはソフトリンクではない場合、それはハードリンクすべきですか? –

+0

通常のファイル*は*ハードリンクです。 – wildplasser

答えて

2

しかし、リンクがハードリンクであることをどのように認識できますか?

できません。

"ハードリンク"は実際には特別なものではありません。これは、ディレクトリエントリと同じディスク上の同じデータを指し示すディレクトリエントリです。 ハードリンクを確実に識別するには、すべてのファイルシステム上のパスをinodeにマップし、どのファイルが同じ値を指しているのかを確認します。

0

struct statには、ハードリンク数に対するst_nlinkメンバーがあります。それは> 1です。実際のファイルコンテンツへのハードリンクの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 
関連する問題