不完全的uptime

#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,&current_record,len_of_utmp);
  print_up(current_record.ut_time);
  while(read(fd,&current_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);
  }
}

对比:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值