首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用户在网上使用wtmp的时间

用户在网上使用wtmp的时间
EN

Stack Overflow用户
提问于 2013-12-07 18:00:31
回答 1查看 751关注 0票数 1

在使用wtmp时,我能够获得用户登录的tty、登录时间和更多信息。但是,我想知道用户在网上花费了多少时间。有什么办法可以得到注销时间吗?

谢谢,

代码语言:javascript
复制
#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);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-07 18:19:33

从“最后”命令的源代码中,您可以从2.88dsf.orig.tar.gz下载(一旦下载完毕,解压缩并检查sysvinit-2.88dsf/src/last.c):

代码语言:javascript
复制
    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);
        }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20444663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档