• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
游浩贤
博客园    首页    新随笔    联系   管理    订阅  订阅

用系统调用实现who命令——mywho

用系统调用实现who命令——mywho

who功能

man who

utmp

man utmp

查看具体功能:

可以发现utmp可以显示登陆者的pid、登陆设备、登陆者的名字、登录主机的名字、退出状态等等,其中,登录时间被保存在tu_tv中。

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,&current_record,reclen)==reclen)
                showinfo(&current_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);
}
  • 在标准C/C++中,我们可通过tm结构来获得日期和时间, tm结构 在time.h中的定义如下:
struct tm {
          int tm_sec;       /* 秒 – 取值区间为[0,59] */
          int tm_min;       /* 分 - 取值区间为[0,59] */
          int tm_hour;      /* 时 - 取值区间为[0,23] */
          int tm_mday;      /* 一个月中的日期 - 取值区间为[1,31] */
          int tm_mon;       /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */
          int tm_year;      /* 年份,其值等于实际年份减去1900 */
          int tm_wday;      /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */
          int tm_yday;      /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */
          int tm_isdst;     /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/
          };

运行截图

posted @ 2022-10-14 11:10  游浩贤  阅读(61)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3