2
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
    struct stat buf;
    int fd;

    if (fd = open(argv[1], O_RDWR | O_CREAT)<0)
    {
        printf("file open error\n");
        return 1;
    }
    if (link(argv[1], "link1") + link(argv[1], "link2")<0)
    {
        printf("error link\n");
        return 1;
    }
    if (fstat(fd, &buf)<0)
    {
        printf("error fstat\n");
        return 1;
    }
    printf("nlinks before = %d \n", buf.st_nlink);
    if (unlink("link2") + unlink("link1") + unlink(argv[1])<0)
    {
        printf("unlink error\n");
        return 1;
    }
    if (fstat(fd, &buf)<0)
    {
        printf("error fstat\n");
        return 1;
    }
    printf("nlinks after = %d \n", buf.st_nlink);
    return 0;
}

输出: nlinks before = 1 nlinks after = 1

为什么 st_nlink 总是 = 1 即使文件至少有 3 个链接?另外,如果我改用,lstat我会得到 3 个 st_nlinks。为什么?

4

1 回答 1

5
if (fd = open(argv[1], O_RDWR | O_CREAT)<0)

应该:

if ( (fd = open(argv[1], O_RDWR | O_CREAT))<0) 

as<优先级高于=.

于 2012-11-21T06:02:34.173 回答