利用 <utmp.h> 提供的 getutent() 遍歷 /var/log/wtmp (或 /var/log/btmp) 中的 utmp 結構,篩選 ut_user == "shutdown" 的記錄,即可取得歷次關機時間。適用於安全稽核、系統可用性分析。
#include <stdio.h>
#include <stdlib.h>
#include <utmp.h>
#include <time.h>
#include <string.h>
int main() {
struct utmp *u;
FILE *fp = fopen("shutdown_note", "w+");
if (!fp) { perror("fopen"); return 1; }
utmpname("/var/log/wtmp"); // 指定 wtmp 路徑
setutent(); // 重置游標到開頭
while ((u = getutent()) != NULL) {
if (strncmp(u->ut_user, "shutdown", 8) == 0) {
time_t t = u->ut_tv.tv_sec;
fprintf(fp, "%s time: %s", u->ut_user, ctime(&t));
}
}
endutent();
fclose(fp);
return 0;
}
utmpname():指定要讀取的 utmp/wtmp 檔案路徑 (預設 _PATH_UTMP)。setutent()/endutent():重置/關閉 utmp 存取游標。getutent():逐筆讀取下一筆記錄,回傳指向靜態緩衝區的指標。ut_user:使用者名稱欄位,關機記錄固定為 "shutdown"。ut_tv.tv_sec:時間戳 (time_t,秒數),搭配 ctime() 轉為可讀字串。/var/log/wtmp (通常 644 root:utmp)。ut_type 為 BOOT_TIME、RUN_LVL、LOGIN_PROCESS、USER_PROCESS、DEAD_PROCESS 等記錄。last、lastb、lastlog 指令可快速查看而不寫程式。