pututline() 和 pututxline() 函数的原型分别如下:
[C++] 纯文本查看 复制代码
#include <utmp.h>
struct utmp *pututline(struct utmp *ut);
#include <utmpx.h>
struct utmpx *pututxline(const struct utmpx *);
这两个函数的作用相同,但根据新的标准,在新编写的应用程序中应该使用 pututxline() 。该函数将参数 ut 所指的 utmp 的记录写到 utmp 文件中,它首先会用 getutxid() 取得正确的写入位置,如果找到,就在那插入记录,否则就将记录添加到 utmp 的文件末尾。
测试代码:
[C++] 纯文本查看 复制代码 #include <stdio.h>
#include <string.h>
#include <utmp.h>
#include <utmpx.h>
int main()
{
struct utmpx ut;
bzero(&ut, sizeof(struct utmpx));
ut.ut_type = USER_PROCESS; //普通用户进程
ut.ut_pid = getpid(); //本进程PID
strncpy(ut.ut_user, "beyes", 5);
strncpy(ut.ut_line, "pts/4", 5);
strncpy(ut.ut_id, "/4", 2);
strncpy(ut.ut_host, "groad.net", strlen("groad.net"));
time((time_t *)&ut.ut_tv.tv_sec); /* 标记时间 */
setutxent();
pututxline(&ut);
sleep(60); /* 悬停 1 分钟来观察*/
endutxent();
return 0;
}
在程序运行后(一般情况下只有 root 或者 utmp 组的用户才有权限运行并修改 utmp 文件),会在中途停留 1 分钟后才会退出,这是为了能够用 who 观察到记录生效的情况.
运行程序:su -c ./pututxline
Password: //这里输入 root 密码 在另一个终端窗口里运行 who 命令观察:beyes@linux-xh53:~/shell/moko> who
beyes :0 2012-01-02 09:07 (console)
beyes pts/0 2012-01-02 09:07
beyes pts/4 2012-01-02 17:17 (groad.net)
beyes pts/2 2012-01-02 11:27 (192.168.1.100) 上面我们看到设置生效了。当程序退出后,再运行 who 程序观察,该记录不存在。但是这不能说明该条记录就从 utmp 文件里删除了,这种情况我们可以运行这篇文章《》里所写的程序来观察:
由上可见,可以看到上面设置的记录还是存在的,那么为什么在程序退出时运行 who 命令时又确实看不到用户“在线”了呢?这是因为,who 命令不仅仅是简单的读取 utmp 来判断的,而是还会依据 wtmp 文件中的记录跟踪信息。如果在 wtmp 文件里发现进程退出或者用户登出,那么 who 即使在 utmp 里读到之前设置的记录,它也会认为用户已经登出。这里可以运行 last 命令来查看:beyes@linux-xh53:~/shell/moko> last |more
beyes pts/4 groad.net Mon Jan 2 17:10 gone - no logout 上面,gone 表示进程已经退出,no logout 表示用户或者进程是没有正常登出的。因此,当 who 发现这样的记录时,它也会知道该“用户”当前并没有登录到系统。注意的是,who 是查看当前所登录的用户! |