Understanding Unix/Linux Programming-who指令练习
Posted Hao的杂货店
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Understanding Unix/Linux Programming-who指令练习相关的知识,希望对你有一定的参考价值。
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 10 #define NRECS 16 11 #define NULLUT ((struct utmp * ) NULL ) 12 #define UTSIZE (sizeof(struct utmp)) 13 14 #define SHOWHOST 15 16 static char utmpbuf[NRECS * UTSIZE] ; 17 static int num_recs ; 18 static int cur_rec ; 19 static int fd_utmp = -1 ; 20 21 void show_info(struct utmp * utbufp) ; 22 void show_time(time_t timeval); 23 24 int utmp_open(char *); 25 int utmp_reload(void); 26 struct utmp * utmp_next(void); 27 void utmp_close(void); 28 29 int main(){ 30 struct utmp * utbufp ; 31 struct utmp * utmp_next() ; 32 33 if( utmp_open( UTMP_FILE ) == -1 ){ 34 perror(UTMP_FILE ); 35 exit(1); 36 } 37 38 while( (utbufp = utmp_next()) != ((struct utmp * ) NULL)){ 39 show_info(utbufp); 40 } 41 42 utmp_close(); 43 return 0 ; 44 45 } 46 47 void show_info(struct utmp * utbufp ){ 48 if( utbufp->ut_type != USER_PROCESS) 49 return; 50 51 printf("%-8.8s" , utbufp->ut_name ); 52 printf(" "); 53 printf("%-8.8d" , utbufp->ut_type ); 54 printf(" "); 55 printf("%-8.8s" , utbufp->ut_line); 56 printf(" "); 57 show_time(utbufp->ut_time); 58 59 #ifdef SHOWHOST 60 printf("(%s)", utbufp->ut_host); 61 #endif 62 printf("\n"); 63 //printf("One Done!\n"); 64 65 } 66 67 void show_time(long timeval) 68 { 69 char * cp ; 70 cp = ctime(& timeval); 71 printf("%12.12s" , cp + 4 ); 72 } 73 74 int utmp_open( char * filename ){ 75 fd_utmp = open(filename , O_RDONLY ); 76 } 77 78 struct utmp * utmp_next(void){ 79 struct utmp * recp ; 80 if( fd_utmp == -1 ){ 81 return NULLUT ; 82 } 83 if( cur_rec == num_recs && utmp_reload() == 0 ){ 84 return NULLUT ; 85 } 86 87 recp = (struct utmp * ) & utmpbuf[cur_rec * UTSIZE]; 88 cur_rec ++ ; 89 return recp ; 90 } 91 92 int utmp_reload(void) 93 { 94 int amt_read ; // file read , fd 95 amt_read = read(fd_utmp , utmpbuf , NRECS * UTSIZE ); 96 num_recs = amt_read/UTSIZE ; 97 cur_rec = 0 ; 98 return num_recs ; 99 } 100 101 void utmp_close(void){ 102 if(fd_utmp != -1 ){ 103 close(fd_utmp ); 104 } 105 }
就不加注释啦,书本上并没有给出完整代码,我就简单完善下啦。
简单地运用了缓冲的思想。
在OpenSuse Leap42.1下编译运行通过。
以上是关于Understanding Unix/Linux Programming-who指令练习的主要内容,如果未能解决你的问题,请参考以下文章
Understanding Unix/Linux Programming-stty指令练习
PyTorch 101 Part 1: Understanding Graphs, Automatic Differentiation and Autograd