一、概述
Linux ctime,即 Change Time,是指 Linux 文件系统记录每个文件或目录的最近状态更改时间,也就是说,当文件或目录的权限、所有权、内容等发生更改时,其 ctime 属性就会被更新。与之相似的还有 access time 和 modification time。
二、 ctime 属性分析
1. 创建文件、修改属性
当文件或目录被创建时,他们的 ctime 属性会被设置为当前时间。具体的实现是在 ext3、ext4、xfs 等文件系统的 inode 中的 i_ctime
字段记录下这个时间。当文件或目录的某些属性被修改时,如权限、所有权等,也会使其 ctime 属性被更新。
#include <stdio.h>
#include <sys/stat.h>
int main() {
const char* path = "/path/to/file";
struct stat file_stat;
stat(path, &file_stat);
printf("ctime: %ld\n", file_stat.st_ctime);
return 0;
}
2. 文件内容修改
如果文件或目录的内容被修改,则其 ctime 属性依然会被更新,但需注意的是,当文件内容被修改,但该文件不保存在内存中时,操作系统会将该文件从磁盘中读取到内存中,此时的 ctime 是读取时间而非修改时间。
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
const char* path = "/path/to/file";
struct stat file_stat;
int fd;
fd = open(path, O_RDWR);
write(fd, "hello world", 11);
stat(path, &file_stat);
printf("ctime: %ld\n", file_stat.st_ctime);
close(fd);
return 0;
}
3. 删除文件或目录
当文件或目录被删除时,其 ctime 属性会被修改,但这个时间并不是文件或目录真正被删除的时间,而是它的目录的 mtime 字段所记录的时间,原因是 Linux 文件系统将每个文件或目录都看作是目录树的一个节点,当节点的文件或目录被删除时,该节点所在的目录的 mtime 就可以被更新。
#include <stdio.h>
#include <unistd.h>
int main() {
const char* path = "/path/to/file";
int ret;
ret = unlink(path);
if (ret == 0) {
printf("File %s is deleted successfully.\n", path);
} else {
printf("Failed to delete file %s.\n", path);
}
return 0;
}
三、小结
实际上,ctime 是文件或目录的状态修改时间,而不是内容修改时间,它包括了文件或目录的创建、属性更新和删除时间等。了解 ctime 的特点与用法,对于 Linux 文件系统管理和调试都是非常重要的。