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?
Asked
Active
Viewed 505 times
1 Answers
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
-
it don't provide shutdown time. i can get BOOT_TIME using getutent api. – Ravi Bhushan Apr 29 '16 at 05:47
-
-
If condition doesn't satisfy. i have printed "ut.ut_user" before if condition. there is no user "shutdown". i am getting user reboot, runlevel, and normal user. – Ravi Bhushan Apr 29 '16 at 07:06
-
@RaviBhushan maybe post your entire code? it works for me, see my code. – fluter Apr 29 '16 at 07:52