实现who
用系统调用实现who命令mywho
使用man who 和man -k utmp进行学习
代码:
#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);
}
运行结果截图对比: