实现who
学习目标
用系统调用实现who命令mywho
注意时间格式要与系统中的who一致
查看who命令的功能
![]()
使用man who查看详细内容

输入man -k utmp

输入man utmp,可以看到utmp的结构
struct utmp { short ut_type; /* Type of record */ pid_t ut_pid; /* PID of login process */ char ut_line[UT_LINESIZE]; /* Device name of tty - "/dev/" */ char ut_id[4]; /* Terminal name suffix, or inittab(5) ID */ char ut_user[UT_NAMESIZE]; /* Username */ char ut_host[UT_HOSTSIZE]; /* Hostname for remote login, or kernel version for run-level messages */ struct exit_status ut_exit; /* Exit status of a process marked as DEAD_PROCESS; not used by Linux init (1 */ /* The ut_session and ut_tv fields must be the same size when compiled 32- and 64-bit. This allows data files and shared memory to be shared between 32- and 64-bit applications. */ #if __WORDSIZE == 64 && defined __WORDSIZE_COMPAT32 int32_t ut_session; /* Session ID (getsid(2)), used for windowing */ struct { int32_t tv_sec; /* Seconds */ int32_t tv_usec; /* Microseconds */ } ut_tv; /* Time entry was made */ #else long ut_session; /* Session ID */ struct timeval ut_tv; /* Time entry was made */ #endif int32_t ut_addr_v6[4]; /* Internet address of remote host; IPv4 address uses just ut_addr_v6[0] */ char __unused[20]; /* Reserved for future use */ };

编写mywho
#include <stdio.h> #include <stdlib.h> #include <utmp.h> #include <fcntl.h> #include <unistd.h> #include <time.h> #define SHOWOST void showinfo(struct utmp *utbufp); long showtime(long timeval); int main() { struct utmp current_record; int utmpfd; int reclen = sizeof(current_record); if((utmpfd = open(UTMP_FILE,O_RDONLY))==-1) { perror(UTMP_FILE); exit(1); } while (read(utmpfd,¤t_record,reclen)==reclen) showinfo(¤t_record); close(utmpfd); return 0; } void showinfo(struct utmp *utbufp){ if(utbufp->ut_type!=USER_PROCESS) return; else{ printf("%-8.8s",utbufp->ut_name); printf(" "); printf("%-8.8s",utbufp->ut_line); printf(" "); showtime(utbufp->ut_time); printf(" "); printf("(%s)",utbufp->ut_host); printf("\n"); } } long showtime(long timeval) { struct tm *cp; cp = gmtime(&timeval); printf(" "); printf("%d-%d-%d %d:%d ",cp->tm_year+1900,cp->tm_mon+1,cp->tm_mday,(cp->tm_hour+8)%24,cp->tm_min); }

浙公网安备 33010602011771号