繁体   English   中英

Linux:以编程方式获取系统关闭时间?

[英]Linux: programmatically get system shutdown time?

我从文件 /proc/uptime 获得 Linux 正常运行时间。 从哪里获得机器上次关机时间。 如何从“c”中的wtmp文件中读取它。 我不想解析最后一个 -x 命令的输出。 我可以使用 sysctl 吗?

在 Linux 上,这种数据是通过getutent api 调用访问的。 您可以使用utmpname设置文件名,并使用getutent获取登录历史记录中的每个条目。

有关 API 结帐的详细信息http://linux.die.net/man/3/getutent

该文件的格式在http://linux.die.net/man/5/utmp 中有描述

编辑

具体如何获取关机时间,检查API返回的struct utmput_user ,如果是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
....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM