带缓冲的who的编写实例

程序读取磁盘上的数据只能通过系统调用read,而read得代码在内核中,所以当read调用发生时,执行权会从用户代码转移到内核代码,而这种来回的切换也是需要时间的,因此可以设置缓冲区以减少切换所带来的时间消耗。

//who.c文件
#include <stdio.h> #include <utmp.h> #include <fcntl.h> #include <unistd.h> #include <time.h> #define SHOWHOST void showtime(long); void show_info(struct utmp*); 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) { struct tm *tvp; tvp = gmtime(&timeval); printf("%d-%d-%d %d:%d",tvp->tm_year+1990,tvp->tm_mon+1,tvp->tm_mday,tvp->tm_hour,tvp->tm_min); } int main() { struct utmp * utmpfp; int reclen = sizeof(*utmpfp); if(utmp_open(UTMP_FILE) == -1) { perror(UTMP_FILE); _exit(1); } while((utmpfp = utmp_next()) != (struct utmp *) NULL) { show_info(utmpfp); } utmp_close(); return 0; }

具体的文件读入操作

//utmplib.c
#include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <utmp.h> #define NRECS 16 //缓存区个数 #define NULLUT ((struct utmp *)NULL) #define UTSIZE (sizeof(struct utmp)) //缓冲区单位大小 static char utmpbuf[NRECS * UTSIZE];//缓冲区 static int num_recs; static int cur_rec; static int fd_utmp = -1; utmp_open(char *filename) { 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) //没有可读的数据时返回空指针 { return NULLUT; } recp = (struct utmp *)&utmpbuf[cur_rec * UTSIZE]; //返回当前指向的缓冲的地址 cur_rec++;//当前缓冲单元位置递增 return recp;//返回缓冲单元指针 } int utmp_reload() { int amt_read; amt_read = read(fd_utmp,utmpbuf,NRECS * UTSIZE); //从文件读入到缓冲区 num_recs = amt_read/UTSIZE;//计算读入的缓冲数量 cur_rec = 0;//重置为0 return num_recs;//返回缓冲数 } void utmp_close() { if(fd_utmp != -1) //如果已经打开 { close(fd_utmp);//关闭打开的文件 } }
原文地址:https://www.cnblogs.com/hlb430/p/2627334.html