gpt4 book ai didi

c - 用户使用 wtmp 在线花费的时间

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:03 25 4
gpt4 key购买 nike

在使用 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);
}

最佳答案

来自“last”命令的源代码,您可以从 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);
}

关于c - 用户使用 wtmp 在线花费的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20444663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com