美文网首页
Linux文件时间之atime、mtime、ctime

Linux文件时间之atime、mtime、ctime

作者: 高级程序狗 | 来源:发表于2020-02-01 18:12 被阅读0次

Linux文件有三种时间,访问时间(access time)、修改时间(modify time)、变更时间(change time)。那么它们有什么区别呢?

在CentOS 7下输入man 2 stat,可以看到三种时间的说明:

st_atime
      This is the file's last access timestamp.  It is changed by file
      accesses,   for   example,   by  execve(2),  mknod(2),  pipe(2),
      utime(2), and read(2) (of more than  zero  bytes).   Other  rou‐
      tines, like mmap(2), may or may not update st_atime.
st_mtime
      This  is  the file's last modification timestamp.  It is changed
      by file modifications, for example,  by  mknod(2),  truncate(2),
      utime(2),  and  write(2)  (of  more than zero bytes).  Moreover,
      st_mtime of a directory is changed by the creation  or  deletion
      of  files  in that directory.  The st_mtime field is not changed
      for changes in owner, group, hard link count, or mode.
st_ctime
      This is the file's last status change timestamp.  It is  changed
      by  writing or by setting inode information (i.e., owner, group,
      link count, mode, etc.).

从中可以看出:

  • atime:这是文件最后访问时间,例如:execve(2)执行、mknod(2)创建、pipe(2)创建数据管道、utime(2)改变最后访问和修改时间、read(2)读取大于0字节,等操作会更新访问时间。
  • mtime:这是文件最后修改时间。mknod(2)创建、truncate(2)截断、utime(2)改变最后访问和修改时间、write(2)写入超过0字节。除此之外,在文件夹内创建或删除文件会更新文件夹的修改时间。修改用户、用户组、模式(rwx),增加硬链接,不会改变文件的修改时间。
  • ctime:这是文件最后状态变更时间。写入、设置inode信息(修改用户、用户组、模式(rwx),增加硬链接等),会更新变更时间。

ps:函数可以通过此页面查询。

为何执行cat后,atime没有更新?

Not all of the Linux filesystems implement  all  of  the  time  fields.
Some  filesystem  types  allow  mounting in such a way that file and/or
directory accesses do not cause an update of the st_atime field.   (See
noatime,  nodiratime, and relatime in mount(8), and related information
in mount(2).)  In addition, st_atime is not updated if a file is opened
with the O_NOATIME flag; see open(2).

一些文件系统允许在挂载时指定文件或者文件夹访问时不改变atime。参见mount(8)中的noatimenodiratimerelatime
其中relatime是很多文件系统的默认行为,意思是只有在上一次访问时间早于当前修改或更改时间时,才会更新访问时间,也是为什么执行cat后未atime未更新的原因。
此外,可以通过mount命令设置atime行为,sudo mount -t tmpfs -o strictatime tmpfs /mnt

如何手动设置mtime?

有时候会有一些特殊的需要,比如修改了文件不想让别人知道=。=
这时我们需要使用touch命令:
touch -mad 2018-03-10 13:29:19.351159892 file1
其实m参数表示mtime,a表示atime,d表示使用string格式设定档案的时间记录。
注意这里如果使用t参数,只能设置时间到秒,容易穿帮[[CC]YY]MMDDhhmm[.ss]

相关文章

网友评论

      本文标题:Linux文件时间之atime、mtime、ctime

      本文链接:https://www.haomeiwen.com/subject/mpkxxhtx.html