自己动手编写一个简单的who命令(不带参数)

转自: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*/
}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值