搜索

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


发布时间: 2022-11-24 18:30:04    浏览次数:62 次

用系统调用实现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()为负。*/
          };

运行截图

免责声明 用系统调用实现who命令——mywho,资源类别:文本, 浏览次数:62 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-24 06:30:04。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/marryj/p/16790998.html