曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 3988|回复: 0
打印 上一主题 下一主题

[进程] getutline()/getutxline() -- 从 utmp 中查找相应记录

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
跳转到指定楼层
楼主
发表于 2012-1-1 23:28:49 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
getutxline() 和 getutxline() 原型分别如下:
[C++] 纯文本查看 复制代码
#include <utmp.h>
struct utmp *getutline(struct utmp *ut);
#include <utmpx.h>
struct utmpx *getutxline(const struct utmpx *);

getutline() 和 getutxline() 是同功能函数,但在新编写的应用程序中应该使用后者。这两个函数是从 utmp 文件的当前读写位置逐条往后查找 ut_type 为 USER_PROCESS 或 LOGIN_PROCESS 的记录,并且 ut_line 要和 ut->line 相符。找到相符的记录后比返回该条记录的指针。关于 utmp 结构可参考:http://www.groad.net/bbs/read.php?tid-5805.html

测试代码
[C++] 纯文本查看 复制代码
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <utmp.h>
#include <utmpx.h>

void print_record (const struct utmpx *ut, const char *type)
{
    struct utmpx *utp;
    while ((utp = getutxline(ut)) != NULL) {
        printf("%-8s ", utp->ut_user);
        printf("%-9.9s ", type);
        printf ("%-5d %-6.6s %-9.9s %-20.20s ", (long)utp->ut_pid, utp->ut_line, utp->ut_id, utp->ut_host);
        printf ("%s", ctime((time_t *) & (utp->ut_tv.tv_sec)));
    }
}

                       
int main()
{
    struct utmpx ut;


    printf ("User     Type      PID   Line   Id        Host                Date/time\n");

    setutxent();
    ut.ut_type = USER_PROCESS;
    strncpy(ut.ut_line, "pts/1", strlen("pts/1"));
    print_record (&ut, "USER_PROCESS");
    endutxent();
    

    return 0;
}

运行输出:
./getutxline
User     Type      PID   Line   Id        Host                Date/time
beyes    USER_PROC 4513  pts/1  /1        192.168.1.100        Sun Jan  1 12:01:44 2012
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-6-18 06:35 , Processed in 0.066418 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表