Reputation: 13
While using wtmp, i was able to get the tty of the user login, the time of login and more information. however, I want to be able to know how much time the user spent online. Is there a way to get the logout time ?
Thanks,
#define WTMP "/var/log/wtmp"
#define K 1024
int main()
{
struct utmp w;
FILE *fd;
time_t t;
struct tm *timeinfo;
char buffer[K];
fd = fopen(WTMP, "r");
if(fd == NULL) {
fprintf(stderr, "cannot open %s\n", WTMP);
exit(0);
}
while(fread(&w, sizeof(struct utmp), 1, fd) == 1) {
if(w.ut_type == USER_PROCESS) {
if( strcmp(w.ut_user, "user1") == 0) {
/* get time in seconds, convert to struct tm, make printable formate*/
t = w.ut_tv.tv_sec;
timeinfo = localtime (&t);
strftime (buffer, K, "%a %b %e %R (EST)", timeinfo);
printf("time: %s Login tty: %s\n", buffer, w.ut_line);
}
}
}
fclose(fd);
}
Upvotes: 1
Views: 1068
Reputation: 9819
From the source code of the "last" command, which you can download from http://ftp.de.debian.org/debian/pool/main/s/sysvinit/sysvinit_2.88dsf.orig.tar.gz (once you have the download, unpack it and check sysvinit-2.88dsf/src/last.c):
case USER_PROCESS:
/*
* This was a login - show the first matching
* logout record and delete all records with
* the same ut_line.
*/
c = 0;
for (p = utmplist; p; p = next) {
next = p->next;
if (strncmp(p->ut.ut_line, ut.ut_line,
UT_LINESIZE) == 0) {
/* Show it */
if (c == 0) {
quit = list(&ut, p->ut.ut_time,
R_NORMAL);
c = 1;
}
if (p->next) p->next->prev = p->prev;
if (p->prev)
p->prev->next = p->next;
else
utmplist = p->next;
free(p);
}
}
/*
* Not found? Then crashed, down, still
* logged in, or missing logout record.
*/
if (c == 0) {
if (lastboot == 0) {
c = R_NOW;
/* Is process still alive? */
if (ut.ut_pid > 0 &&
kill(ut.ut_pid, 0) != 0 &&
errno == ESRCH)
c = R_PHANTOM;
} else
c = whydown;
quit = list(&ut, lastboot, c);
}
Upvotes: 3