#include<stdio.h>
#include<utmp.h>
#include<fcntl.h>
#include<unistd.h>
#include<time.h>
#define SECONDS_ONE_YEAR (3600*24*365)
#define SECONDS_ONE_DAY (3600*24)
#define SECONDS_ONE_HOUR 3600
#define SECONDS_ONE_MIN 60
void print_up(long);
int main()
{
struct utmp current_record;
int len_of_utmp;
int fd;
int num_of_users=0;
len_of_utmp=sizeof(struct utmp);
if((fd=open(UTMP_FILE,O_RDONLY))==-1){
perror("Cannot open file");
}
read(fd,¤t_record,len_of_utmp);
print_up(current_record.ut_time);
while(read(fd,¤t_record,len_of_utmp)==len_of_utmp){
if(current_record.ut_type==USER_PROCESS){
num_of_users++;
}
}
close(fd);
printf(" %d user,\n",num_of_users);
return 0;
}
void print_up(long time_boot)
{
long time_now,time_up;
struct tm* uptm;
int year,day,hour,min;
time_now=time(NULL);
time_up=time_now-time_boot;
printf("%.9s up",ctime(&time_now)+10);
year=time_up/SECONDS_ONE_YEAR;
time_up=time_up%SECONDS_ONE_YEAR;
day=time_up/SECONDS_ONE_DAY;
time_up=time_up%SECONDS_ONE_DAY;
hour=time_up/SECONDS_ONE_HOUR;
time_up=time_up%SECONDS_ONE_HOUR;
min=time_up/SECONDS_ONE_MIN;
if(year>0){
printf(" %d",year);
if(year==1){
printf(" year,");
}
if(year>1){
printf(" years,");
}
}
if(day>0){
printf(" %d",day);
if(day==1){
printf(" day,");
}
if(day>1){
printf(" days,");
}
}
if(hour>0){
printf(" %2d:",hour);
printf("%.2d,",min);
}
if(hour==0){
printf(" %d min,",min);
}
}
对比: