使用wtmp时,我能够获得用户登录的tty,登录时间和更多信息。但是,我希望能够知道用户在线上花了多少时间。有没有办法获得退出时间?
谢谢,
#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);
}
答案 0 :(得分:3)
从“最后一个”命令的源代码,您可以从http://ftp.de.debian.org/debian/pool/main/s/sysvinit/sysvinit_2.88dsf.orig.tar.gz下载(一旦下载,解压缩并检查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);
}