自己动手编写一个简单的who命令(不带参数)
2012-12-03 00:23
567 查看
转自:http://blog.csdn.net/bookworm1987/article/details/6565430
最近在学习Linux程序设计,查阅了相关的资料,自己写了一个who命令。
1.who命令的作用
显示当前登陆的用户和时间
2.who命令的原理
在linux中查找联机帮助,可以看到,在linux中,登陆用户的信息存放在文件user/var/run/utmp中(不同版本的linux可能不同),该文件 中有一个utmp结构体,用来存储用户的信息。故who的主要原理就是获取这个结构体里的信息并显示在屏幕上。
3.实现代码
最近在学习Linux程序设计,查阅了相关的资料,自己写了一个who命令。
1.who命令的作用
显示当前登陆的用户和时间
2.who命令的原理
在linux中查找联机帮助,可以看到,在linux中,登陆用户的信息存放在文件user/var/run/utmp中(不同版本的linux可能不同),该文件 中有一个utmp结构体,用来存储用户的信息。故who的主要原理就是获取这个结构体里的信息并显示在屏幕上。
3.实现代码
/*the implementation of the who command author:bookworm data:6.23.2011 */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <utmp.h> #include <unistd.h> #include <time.h> #define SHOWHOST void show_info(struct utmp * utbuf); void show_time(long int timeval); int main() { struct utmp current_record; int utmpfd; /*the descriptor*/ int reclen; /*length of the utmp struct*/ reclen = sizeof(current_record); /*open the file*/ utmpfd = open(UTMP_FILE,O_RDONLY); if(utmpfd == -1) { perror("open error"); exit(1); } /*read from the opened utmp file*/ while((read(utmpfd,¤t_record,reclen) == reclen)) { show_info(¤t_record); /*call the function to display the contens of the struct*/ } close(utmpfd); return 0; } /* show_info function this function is uesd to display the contens of the utmp struct */ void show_info(struct utmp * utbuf) { if(utbuf->ut_type != USER_PROCESS) return; printf("%-8.8s",utbuf->ut_name); printf(" "); printf("%-8.8s",utbuf->ut_line); printf(" "); show_time(utbuf->ut_time); printf(" "); #ifdef SHOWHOST printf("(%s)",utbuf->ut_host); #endif printf("/n"); } /*display the time */ void show_time(long int timeval) { char * cp; cp = ctime(&timeval); /*transform the format from the time_t to the format that human can read*/ printf("%12.12s",cp+4); /*get the datas from position 4*/ }
相关文章推荐
- 自己动手编写一个简单的who命令(不带参数)
- 编写自己的shell解析器(一)一个简单的循环命令输入和历史打印
- Linux_自己编写一个who命令
- 自己动手编写一个简单的U盘杀毒程序
- 自己动手写一个简单的ping命令(windows下)
- linux系统编程:自己动手写一个who命令
- 自己动手写一个简单的Shell之一:了解Shell
- 自己动手封装一个url参数解释器( ghostWuUrlParser.js )
- 自己动手写最简单的Android驱动---LED驱动的编写【转】
- linux系统编程:自己动手写一个pwd命令
- 自己动手系列——实现一个简单的ArrayList
- 自己动手模拟开发一个简单的Web服务器
- 自己动手编写一个VS插件(二)——理解OnConnection函数
- 使用hadoop命令rcc生成Record 一个简单的方法来实现自己的定义writable对象
- 自己动手实现一个简单的Ajax
- 自己编写who命令
- 自己动手系列——实现一个简单的LinkedList
- 自己动手编写一个VS插件(四)——创建工具栏之二
- 自己动手编写一个VS插件(二)——理解OnConnection函数
- 自己动手写一个简单的MVC框架(第一版)