【C语言】实现Linux下的who命令
2016-05-17 21:19
495 查看
【C语言】实现Linux下的who命令
实现思路是读取UTMP_FILE文件,利用结构体struct utmp去获取相应的消息。代码实现
#include <stdio.h> #include <stdlib.h> #include <utmp.h> #include <fcntl.h> #include <unistd.h> #include <time.h> #define SHOWHOST void showtime(long timeval) { struct tm *t; t = localtime(&timeval); if(t->tm_mon+1 < 10) printf("%d-0%d", t->tm_year+1900, t->tm_mon+1); else printf("%d-%d", t->tm_year+1900, t->tm_mon+1); printf("-"); if(t->tm_mday+1 < 10) printf("0%d", t->tm_mday); else printf("%d", t->tm_mday); printf(" "); if(t->tm_hour<10) printf("0%d", t->tm_hour); else printf("%d", t->tm_hour); printf(":"); if(t->tm_min<10) printf("0%d", t->tm_min); else printf("%d", t->tm_min); } void show_info(struct utmp * uBuf) { if(uBuf->ut_type != USER_PROCESS) return; printf("%-8.8s", uBuf->ut_name); printf(" "); printf("%-8.8s", uBuf->ut_line); printf(" "); showtime(uBuf->ut_time); printf(" "); #ifdef SHOWHOST printf("(%s)", uBuf->ut_host); printf(" "); #endif printf("\n"); } int main(void) { struct utmp current_record; int utmpfd; int reclen = sizeof(current_record); if( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ) { printf("open file error\n"); exit(1); } while(read(utmpfd, ¤t_record, reclen) == reclen) show_info(¤t_record); close(utmpfd); return 0; }
效果
相关文章推荐
- Linux socket 初步
- Linux Kernel 4.0 RC5 发布!
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- 如何组织构建多文件 C 语言程序(二)
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户
- Scientific Linux 5.5 图形安装教程