1

I am getting Linux uptime from file /proc/uptime. From where to get last shutdown time of machine. how to read it from wtmp file in "c". I don't want parse output of last -x command. can i get using sysctl?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ravi Bhushan
  • 253
  • 3
  • 17
  • What distribution and version number are you using (Ubuntu 14.04, CentOS 7, etc.)? Different init systems may write different info to wtmp. – Mark Plotnick Apr 29 '16 at 17:31

1 Answers1

3

On Linux, this kind of data is access through the getutent api calls. You can use utmpname to set the file name, and use getutent to get every entry in the login history.

For details of the API checkout http://linux.die.net/man/3/getutent

The format of the file is described at http://linux.die.net/man/5/utmp

EDIT

For how to get the shutdown time specifically, check the ut_user of the struct utmp returned by the API, and do something if it's shutdown, for example, loop through all entries in the file with this code:

struct utmp *u = getutent();
if (strncmp(u>ut_user, "shutdown", 8) == 0) {
    // parse the shutdown time in u->ut_time
}

Following code successfully identified all the shutdown entries on my system:

#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;
}

Output on my system:

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
....
fluter
  • 13,238
  • 8
  • 62
  • 100