who 命令编写

该命令模拟系统的 who命令,但是功能没有系统的功能强大

参考 unix/linux 编程实签教程

该命令主要读取系统用户登陆日志文件 utmp文件

文件操作函数的头文件fcntl.h,日志文件记录的结构描述utmp.h

读取函数使用系统读取文件函数 open(char*,int mode),返回int的文件描述符,失败返回-1

读取记录的函数 read(fip,buf,recordlen),返回实际读取的字数

#include<stdio.h>  //printf etc
#include<utmp.h>   //utmp record struct
#include<fcntl.h>  //file read,write mode like O_RDONLY,O_WRONLY,O_RDWR etc
#include<time.h>   //time formate convert
#include<unistd.h> //include open,read,write etc.
#define SHOWHOST
void show_info(struct utmp *rec);
void show_time(long ltime);
int main(int ac,char *av[])
{
int utmpfp;
struct utmp rec;
int reclen=sizeof(rec);
if((utmpfp=open(UTMP_FILE,O_RDONLY))==-1)  //UTMP_FILE define in utmp.h  

UTMP_FILE
=/var/run/utmp
        {
        exit(
1);
        perror(UTMP_FILE);
        }
while(read(utmpfp,&rec,reclen)==reclen)
        show_info(
&rec);
close(utmpfp);
return 0;
}
void show_info(struct utmp *rec)
{
        
if(rec->ut_type!=USER_PROCESS) //define in utmp.h.  mean user normal 

login.
                
return;
        printf(
"%-8.8s",rec->ut_name);
        printf(
" ");
        printf(
"%-8.8s",rec->ut_line);
        printf(
" ");
        
//printf("%10ld",rec->ut_time);
        show_time(rec->ut_time);
#ifdef SHOWHOST
        printf(
"(%s)",rec->ut_host);
        printf(
" ");
#endif
        printf(
"\n");
}
void show_time(long ltime)
{
        
char *tm;
        tm
=ctime(&ltime);
        printf(
"%16.12s",tm+4);
        printf(
" ");
}

 

posted on 2009-04-05 15:45  ringwang  阅读(284)  评论(0编辑  收藏  举报