您的位置:首页 > 其它

自己动手编写一个简单的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.实现代码
/*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*/
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: