对who2使用缓冲技术.
/*who3.c 从buffer中打印who信息
*/
#include <stdio.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#define SHOWHOST
void showtime(long);
void show_info( struct utmp *);
int main()
{
struct utmp *utbufp;
struct utmp *utmp_next();
if( utmp_open( UTMP_FILE ) == -1 )
{
perror( UTMP_FILE );
exit(1);
}
while( (utbufp = utmp_next()) != ((struct utmp *)NULL) ) //utmplib.c utmp_next()的返回值不为NULLUT
show_info( utbufp );
utmp_close();
return 0;
}
void show_info( struct utmp *utbufp)
{
if( utbufp->ut_type != USER_PROCESS )
return;
printf("% -8.8s", utbufp->ut_name);
printf(" ");
printf("% -8.8s", utbufp->ut_line);
printf(" ");
showtime( utbufp->ut_time );
printf(" ");
#ifdef SHOWHOST
printf("(% s)", utbufp->ut_host);
#endif
printf("\n");
}
void showtime( long timeval )
{
char *cp;
cp = ctime(&timeval);
printf("%12.12s", cp+4);
}
/*utmplib.c 从utmp文件中进行buffer read
*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <utmp.h>
#define NRECS 16 //buffer一次读取的utmp数量
#define NULLUT ((struct utmp *)NULL) //指定NULL为utmp_next的返回值 struct utmp *类型
#define UTSIZE (sizeof(struct utmp)) //utmp结构体大小
static char utmpbuf[NRECS * UTSIZE]; //定义buffer大小
static int num_recs; //buffer中实际读取的utmp数量
static int cur_rec; //已经打印的utmp数量
static int fd_utmp = -1;
utmp_open( char *filename ) //打开utmp文件
{
fd_utmp = open( filename, O_RDONLY);
cur_rec = num_recs = 0;
return fd_utmp;
}
struct utmp *utmp_next()
{
struct utmp *recp;
if( fd_utmp == -1 )
return NULLUT;
if( cur_rec == num_recs && utmp_reload() == 0 ) //已经打印数等于实际读取数时,再次reload。如果文件读取完毕时,返回null
return NULLUT;
recp = (struct utmp *) &utmpbuf[ cur_rec * UTSIZE]; //逐个返回utmp地址(cur_rec * UTSIZE)
cur_rec++;
return recp; //返回当前指向的buffer的地址
}
int utmp_reload()
{
int amt_read;
amt_read = read( fd_utmp, utmpbuf, NRECS * UTSIZE ); //读取16个utmp结构体大小的数据到utmpbuf
num_recs = amt_read/UTSIZE; //计算实际读到的utmp数
cur_rec = 0; //重新设置打印数为0
return num_recs;
}
utmp_close()
{
if( fd_utmp != -1) //有打开才关闭
close( fd_utmp );
}