Linux_自己编写一个who命令

本文介绍了Linux下who命令的功能及其实现原理,通过分析man文档、info信息和utmp文件,了解到who命令通过读取/var/run/utmp获取登录用户信息。接着,文章详细讲述了如何编写自己的who命令,包括使用read函数读取utmp文件,筛选USER_PROCESS类型的登录信息,并将时间戳转换为可读日期。最后给出了源码和参考资料。
摘要由CSDN通过智能技术生成

1 分析
1.1 Linux的who命令可以做什么
通过who命令可以查看当前已登录的用户
1.2 linux的who命令是如何实现的
1.2.1 通过man获得信息
在命令行中输入

man who

在帮助文档中没有写出who是如何实现的,但是在最后

SEE ALSO
The full documentation for who is maintained as a Texinfo manual. If
the info and who programs are properly installed at your site, the com-
mand

         info coreutils 'who invocation'

  should give you access to the complete manual.

发现可以再 info中查看更详细的介绍
1.2.2 通过info获得信息
在命令行输入

info coreutils 'who invocation'

在显示的内容中有这么一段话

If given one non-option argument, who' uses that instead of a
default system-maintained file (often
/var/run/utmp’ or
/var/run/utmp') as the name of the file containing the record of users
logged on.
/var/log/wtmp’ is commonly given as an argument to `who’
to look at who has previously logged on.

可以知道默认情况who是读取/var/run/utmp的内容来显示的,如果直接打开该文件,会发现是一段乱码,上网查阅该文件

1.2.3 通过谷歌获取信息
man.org7中可以看到对该文件的描述

The utmp file allows one to discover information about who is
currently using the system. There may be more users currently using
the system, because not all programs use utmp logging.
The file is a sequence of utmp structures, declared as follows in

/* Compatibility names for the strings of the canonical file names.  */
#define UTMP_FILE       _PATH_UTMP
#define UTMP_FILENAME   _PATH_UTMP

但是,在其中包含了一个

/* Get system dependent values and data structures.  */
#include <bits/utmp.h>

于是打开在该目录下的utmp.h



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值