用系统调用实现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,¤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);
}
- 在标准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()为负。*/
};
运行截图
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)