编写who命令-第2版
【编写who命令-第2版】之前写过第1版who命令:
https://www.jianshu.com/p/ac7dce45bd95
缓冲是提高文件I/O效率的方法之一,现在运用缓冲技术写第2版who命令:
分为2个文件utmplib.c和who2.c,who2.c把前一个文件include进来即可。
下面是utmplib.c:
#include
#include
#include
#include
#include
#include
#include
#include #define UTMP_SIZE (sizeof(struct utmp))
#define NUM 3int fd = -1;
int cur_utmp = 0;
int num_utmp = 0;
char utmpbuf[NUM * UTMP_SIZE];
void utmp_open(char *filename) {
if((fd = open(filename, O_RDONLY)) == -1) {
printf("Can't open file %s\n", filename);
exit(1);
}
}int utmp_load() {
int res = read(fd, utmpbuf, NUM * UTMP_SIZE);
num_utmp = res/UTMP_SIZE;
cur_utmp = 0;
return num_utmp;
}struct utmp * utmp_next() {
if (cur_utmp == num_utmp && utmp_load() == 0) {
return (struct utmp *)NULL;
}
return (struct utmp *)&utmpbuf[(cur_utmp++)*UTMP_SIZE];
}void utmp_close() {
if (fd != -1) {
close(fd);
}
}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");
}
下面是who2.c:
#include
#include
#include
#include
#include
#include
#include
#include
#include "utmplib.c"int main() {
utmp_open("/var/run/utmp");
struct utmp *utmp_record;
while ((utmp_record=utmp_next()) != (struct utmp *)NULL) {
show_info(utmp_record);
}
utmp_close();
return 0;
}
推荐阅读
- 标签、语法规范、内联框架、超链接、CSS的编写位置、CSS语法、开发工具、块和内联、常用选择器、后代元素选择器、伪类、伪元素。
- 编写字典程序
- 你命令我爱你吧(原创)
- 用npm发布一个包的教程并编写一个vue的插件发布
- 常用git命令总结
- 用Go构建区块链——3.持久化和命令行
- 《读_Head_First_有感》_“命令模式”
- locate搜索
- 依赖注入模块
- Linux|Linux 服务器nginx相关命令