stat 結構體中有三個 time_t 類型的字段,分别是
st_atime
,
st_mtime
,
st_ctime
.
1 三個時間的含義
1.1 st_atime
檔案最後一次被通路的時間。
調用
creat(), mknod(), pipe(), utime(), and read()
這些函數會改變 st_atime 的值。
1.2 st_mtime
檔案内容最後一次被修改的時間。
調用
creat(), mknod(), pipe(), utime(), and write()
這些函數會改變 st_mtime 的值。
1.3 st_ctime
檔案狀态最後一次被修改的時間,也就是 inode 結構體的内容(不包含這三個時間)最後一次被修改的時間。
調用
chmod(), chown(), creat(), link(2), mknod(), pipe(), unlink(2), utime(), and write()
2 實驗
- 建立一個檔案
.test.txt
- 使用 stat 函數檢視時間。st 程式的代碼見 2.4 節
$ touch test.txt
$ ./st test.txt
上述指令執行完後
st_dev = 2049
st_ino = 831785
st_mode = 33204
st_nlink = 1
st_uid = 1000
st_gid = 1000
st_size = 0
st_atime = 1480336198
st_mtime = 1480336198
st_ctime = 1480336198
2.1 隻修改 st_atime
$ cat text.txt
$ ./st test.txt
執行後
// 無關結果不展示了
st_atime = 1480336855 // 最近通路時間被更改,因為 cat 函數執行了讀檔案的操作
st_mtime = 1480336198
st_ctime
2.2 隻修改 st_mtime
很遺憾,還沒有辦法做到隻修改 st_mtime,修改了 st_mtime,必然會導緻 st_ctime 的更改。想想為什麼?
$ echo 'hello' > test.txt
$ ./st test.txt
執行後
// 無關結果不展示了
st_atime = 1480336855
st_mtime = 1480336973 // 最近更改時間被更改
st_ctime = 1480336973 // 最近狀态被更改
2.3 隻修改 st_ctime
$ chmod o+w test.txt
$ ./st test.txt
執行後
// 無關結果不展示了
st_atime = 1480336855
st_mtime = 1480336973
st_ctime
2.4 st 程式的代碼
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
struct stat st;
int r = stat(argv[1], &st);
if (r) {
perror("stat");
return -1;
}
printf("st_dev = %lld\n", st.st_dev);
printf("st_ino = %ld\n", st.st_ino);
printf("st_mode = %d\n", st.st_mode);
printf("st_nlink = %d\n", st.st_nlink);
printf("st_uid = %d\n", st.st_uid);
printf("st_gid = %d\n", st.st_gid);
printf("st_size = %ld\n", st.st_size);
printf("st_atime = %ld\n", st.st_atime);
printf("st_mtime = %ld\n", st.st_mtime);
printf("st_ctime = %ld\n", st.st_ctime);
return 0;
}