1 /*Apply a Buffer trick in who3.c*/2 3#include <stdio.h>4#include <stdlib.h>5#include <utmp.h>6#include <fcntl.h>7#include <unistd.h>8#include <time.h>9 Ten #defineNrecs 16 One #defineNullut ((struct utmp *) NULL) A #defineUtsize (sizeof (struct utmp)) - - #defineShowhost the - Static CharUtmpbuf[nrecs *Utsize]; - Static intNum_recs; - Static intCur_rec; + Static intFd_utmp =-1 ; - + voidShow_info (structUTMP *UTBUFP); A voidshow_time (time_t timeval); at - intUtmp_open (Char*); - intUtmp_reload (void); - structUtmp * Utmp_next (void); - voidUtmp_close (void); - in intMain () { - structUTMP *UTBUFP; to structUTMP *Utmp_next (); + - if(Utmp_open (utmp_file) = =-1 ){ the perror (utmp_file); *Exit1); $ }Panax Notoginseng - while((UTBUFP = Utmp_next ())! = ((structUTMP *) (NULL)) { the Show_info (UTBUFP); + } A the utmp_close (); + return 0 ; - $ } $ - voidShow_info (structUTMP *UTBUFP) { - if(Utbufp->ut_type! =user_process) the return; - Wuyiprintf"%-8.8s", utbufp->ut_name); theprintf" "); -printf"%-8.8d", utbufp->ut_type); Wuprintf" "); -printf"%-8.8s", utbufp->ut_line); Aboutprintf" "); $Show_time (utbufp->ut_time); - - #ifdef Showhost -printf"(%s)", utbufp->ut_host); A #endif +printf"\ n"); the //printf ("one done!\n"); - $ } the the voidShow_time (Longtimeval) the { the Char*CP; -CP = CTime (&timeval); inprintf"%12.12s", CP +4 ); the } the About intUtmp_open (Char*filename) { theFd_utmp =open (filename, o_rdonly); the } the + structUtmp * Utmp_next (void){ - structUTMP *RECP; the if(Fd_utmp = =-1 ){Bayi returnNullut; the } the if(Cur_rec = = Num_recs && utmp_reload () = =0 ){ - returnNullut; - } the theRECP = (structUtmp *) & Utmpbuf[cur_rec *Utsize]; theCur_rec + + ; the returnRECP; - } the the intUtmp_reload (void) the {94 intAmt_read;//file read, FD theAmt_read = Read (Fd_utmp, UTMPBUF, Nrecs *utsize); theNum_recs = amt_read/utsize; theCur_rec =0 ;98 returnNum_recs; About } - 101 voidUtmp_close (void){102 if(Fd_utmp! =-1 ){103 Close (fd_utmp);104 } the}
View Code
Without comment, the book does not give the complete code, I will simply perfect the next. The idea of buffering is simply applied. The compilation runs through the openSUSE Leap42.1.
From for notes (Wiz)
Understanding unix/linux programming-who Instruction Exercise