ILD

file mtime update granularity
作者:Yuan Jianpeng 邮箱:yuanjp89@163.com
发布时间:2025-12-10 站点:Inside Linux Development

众所周知,mtime是文件的最后修改时间,Time of last modification


在我们的一个项目中,使用mtime判断一个文件是否修改。缓存上一次的mtime,

结果出现了文件修改了,但是mtime没变的情况。出现了bug。


经过研究发现,两次极短的写入,mtime不会变化。


写一个demo验证:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>

void echo(const char *path)
{
        int fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0644);
        if (fd >= 0) {
                write(fd, "123", 3);
                close(fd);
        }
        else
                fprintf(stderr, "open failed: %m\n");
}

int main(int argc, char **argv)
{
        char *path = argv[1];
        struct stat a, b;
        int ret;

        echo(path);
        ret = stat(path, &a);
        if (ret < 0)
                fprintf(stderr, "stat0 failed: %m\n");

        if (argc > 2)
                usleep(atoi(argv[2]));

        echo(path);
        ret = stat(path, &b);
        if (ret < 0)
                fprintf(stderr, "stat1 failed: %m\n");

        printf("old %ld.%ld new %ld.%ld\n",
                a.st_mtim.tv_sec, a.st_mtim.tv_nsec,
                b.st_mtim.tv_sec, b.st_mtim.tv_nsec);

        return 0;
}


写入,读取mtime,再写入,再读取mtime。

执行:

$ sudo ./a.out /run/1

old 1765332504.427453479 new 1765332504.427453479


发现没变,经过AI搜索回答:如果没有经过一个jiffies,那么不更新mtime。


Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.