参考:《Unix-Linux编程实践》
命令功能
使用who命令可以知道有哪些用户正在使用系统,系统是否繁忙,某人是否正在使用系统等。
每一行代表一个已经登录的用户。
第一列表示用户名,第二列表示终端名,第三列为登陆时间,第四列为登录地址。
原理
/var/run/utmp 保存当前在本系统中的用户信息
/var/log/wtmp 保存登陆过本系统的用户信息
who通过读该文件获得信息。
utmp文件中保存的是结构数组,数组元素是utmp类型的结构,可以在utmp.h中找到utmp结构定义。
utmp.h文件在/usr/include目录里(在Unix系统中,大多数的头文件都在/usr/include中)
涉及到的系统调用
打开文件open
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
//pathname 表示文件名字符串
//flags表示打开模式,包括 O_RDONLY, O_WRONLY, O_RDWR(read-only, write-only, read/write)
//返回值:-1 错误,文件描述符 正确。
从文件中读数据read
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
//fd 表示文件描述符
//buf 用来存放数据的目的缓冲区
//count 要读取的字节数
//返回值 -1 错误,读取的字节数 正确
关闭文件close
#include <unistd.h>
int close(int fd);
//fd 表示文件描述符
// -1 错误,0 成功