who命令可以显示出当前系统中已经登录的用户信息。
系统:Ubuntu 16.04.3 LTS (GNU/Linux 4.10.0-35-generic x86_64)
参考书:《Unix/Linux编程实践教程》
下载地址:http://download.csdn.net/download/wdsh13478896311/10213050
阅读联机帮助
$ man who
编写自己的who程序:
- 从文件中读取数据结构
- 将结构中的信息以合适的形式显示出来
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utmp.h>
#include <unistd.h>
#include <time.h>
void show_time(time_t t) {
struct tm *tt = localtime(&t);
printf("%d-%02d-%02d %02d:%02d", tt->tm_year+1900, tt->tm_mon+1, tt->tm_mday, tt->tm_hour, tt->tm_min);
}
void show_info(struct utmp *record) {
if (record->ut_type != USER_PROCESS)
return;
printf("%-8s", record->ut_user);
printf(" ");
printf("%-12s", record->ut_line);
printf(" ");
show_time(record->ut_tv.tv_sec);
printf(" ");
printf("(%s)", record->ut_host);
printf("\n");
}
int main() {
struct utmp cur_record;
int fd = open("/var/run/utmp", O_RDONLY);
if (fd == -1) {
printf("Error!\n");
exit(1);
}
while (read(fd, &cur_record, sizeof(cur_record)) == sizeof(cur_record)) {
show_info(&cur_record);
}
close(fd);
return 0;
}
效果:
xx@xxx:~/xxx$ ./a.out
derc pts/8 2018-01-18 13:21 (106.120.121.131)
xx@xxx:~/xxx$ who
derc pts/8 2018-01-18 13:21 (106.120.121.131)
补充:time_t在哪里定义的(适用于Ubuntu 16.04.3 LTS)
- /usr/include/time.h
# include <bits/types.h>
__BEGIN_NAMESPACE_STD
/* Returned by `time'. */
typedef __time_t time_t;
- /usr/include/x86_64-linux-gnu/bits/types.h
__STD_TYPE __TIME_T_TYPE __time_t; /* Seconds since the Epoch. */
- /usr/include/x86_64-linux-gnu/bits/typesizes.h
#define __TIME_T_TYPE __SYSCALL_SLONG_TYPE
# define __SYSCALL_SLONG_TYPE __SLONGWORD_TYPE
- /usr/include/x86_64-linux-gnu/bits/types.h
#define __SLONGWORD_TYPE long int
补充:printf格式化控制
参考:http://blog.csdn.net/xue_changkong/article/details/41945215