我正在从文件 /proc/uptime 获取 Linux 正常运行时间。从哪里获得机器的最后关机时间。如何从“c”中的 wtmp 文件中读取它。我不想解析 last -x 命令的输出。我可以使用 sysctl 吗?
问问题
344 次
1 回答
3
在 Linux 上,这种数据是通过getutent
api 调用访问的。您可以使用utmpname
设置文件名,并使用getutent
获取登录历史记录中的每个条目。
有关 API 检查的详细信息http://linux.die.net/man/3/getutent
该文件的格式在http://linux.die.net/man/5/utmp有描述
编辑
具体如何获取关机时间,检查API返回ut_user
的struct utmp
,如果是,则做一些事情shutdown
,例如,使用以下代码遍历文件中的所有条目:
struct utmp *u = getutent();
if (strncmp(u>ut_user, "shutdown", 8) == 0) {
// parse the shutdown time in u->ut_time
}
以下代码成功识别了我系统上的所有关闭条目:
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <utmp.h>
int main(void)
{
struct utmp *u;
int ret;
ret = utmpname("/var/log/wtmp");
if (ret < 0) {
perror("utmpname");
return 1;
}
while (true) {
u = getutent();
if (!u) {
perror("getutent");
break;
}
if (strncmp(u->ut_user, "shutdown", 8) == 0) {
time_t t = u->ut_time;
struct tm *tm = localtime(&t);
char timestr[128];
strftime(timestr, sizeof timestr, "%a %b %d %T %Y", tm);
printf("%s: %s\n", u->ut_user, timestr);
}
}
return 0;
}
我的系统上的输出:
shutdown: Tue Mar 08 00:13:00 2016
shutdown: Sat Mar 12 08:45:57 2016
shutdown: Sat Mar 19 09:55:49 2016
shutdown: Wed Mar 23 16:24:39 2016
....
于 2016-04-29T05:25:57.697 回答