getutid() 和 getutxid() 的原型分别如下:
[C++] 纯文本查看 复制代码 #include <utmp.h>
struct utmp *getutid(struct utmp *ut);
#include <utmpx.h>
struct utmpx *getutxid(const struct utmpx *);
两个函数的功能一样,但是在新的应用程序里,应该使用 getutxid() 。这两个函数都是从 utmp 文件的当前位置逐条往后查找 ut 指定的记录。如果 ut->ut_type 为 RUN_LVL, BOOT_TIME, NEW_TIME, 或 OLD_TIME 其中之一,那么就查找与 ut->ut_type 相符合的记录;如果 ut->ut_type 为INIT_PROCESS, LOGIN_PROCESS, USER_PROCESS, 或 DEAD_PROCESS 其中之一,那么就找与 ut->id 相符合的记录。当找到了相符的记录,那么就将该条记录返回,记录的形式当然是 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 = getutxid(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)));
}
printf ("\n");
}
int main()
{
struct utmpx ut;
printf ("User Type PID Line Id Host Date/time\n");
setutxent();
ut.ut_type = RUN_LVL;
print_record (&ut, "RUN_LVL");
endutxent();
setutxent();
bzero(&ut, sizeof(struct utmpx));
ut.ut_type = BOOT_TIME;
print_record (&ut, "BOOT_TIME");
endutxent();
setutxent();
bzero(&ut, sizeof(struct utmpx));
ut.ut_type = USER_PROCESS;
strncpy(ut.ut_id, "/0", 2); /*清零是必须的,因为我们用的是同一个结构*/
print_record (&ut, "USER_PROCESS");
endutxent();
return 0;
}
运行输出: ./getutxid
User Type PID Line Id Host Date/time
runlevel RUN_LVL 53 ~ ~~ 3.1.0-1.2-desktop Sun Jan 1 12:00:25 2012
reboot BOOT_TIME 0 ~ ~~ 3.1.0-1.2-desktop Sun Jan 1 11:59:46 2012
beyes USER_PROC 2434 pts/0 /0 Sun Jan 1 12:00:46 2012 |