1、utmp
utmp文件中储存着登录用户的相关信息(用户名、登录时间。。。。。。)。
通过man utmp可以看到utmp文件的路径
utmp文件中是struct utmp的集合。每一条登录信息对应一个struct utmp记录。
struct utmp在utmp.h头文件中定义。
2、直接读/var/run/utmp文件,便可得到登录用户的信息,参考代码如下。
#include<stdio.h>
#include<utmp.h>
#include<fcntl.h>
#include<unistd.h>
int main() {
struct utmp current_record;
int len_of_utmp;
int fd;
len_of_utmp = sizeof(struct utmp);
if ((fd = open("/var/run/utmp", O_RDONLY)) == -1) {
perror("Cannot open file");
}
while (read(fd, ¤t_record, len_of_utmp) == len_of_utmp) {
printf("%s\n", current_record.ut_name);
}
close(fd);
return 0;
}
3、utmp.h
find / -name utmp.h -print
more /usr/include/utmp.h
more /usr/include/x86_64-linux-gnu/bits/utmp.h
more /usr/include/paths.h
4、UTMP_FILE
由3可见,宏UTMP_FILE的实际值就是"/var/run/utmp"。所以,在编写程序的时候,便可以直接使用UTMP_FILE。
下面的代码只是将上面2中的代码的"/var/run/utmp"替换成了UTMP_FILE,结果一样。
#include<stdio.h>
#include<utmp.h>
#include<fcntl.h>
#include<unistd.h>
int main() {
struct utmp current_record;
int len_of_utmp;
int fd;
len_of_utmp = sizeof(struct utmp);
if ((fd = open(UTMP_FILE, O_RDONLY)) == -1) {
perror("Cannot open file");
}
while (read(fd, ¤t_record, len_of_utmp) == len_of_utmp) {
printf("%s\n", current_record.ut_name);
}
close(fd);
return 0;
}