linux命令编写,编写简单的linux命令

66b52468c121889b900d4956032f1009.png

8种机械键盘轴体对比

本人程序员,要买一个写代码的键盘,请问红轴和茶轴怎么选?

又到了周四分享环节,鉴于最近在看linux编程实践,所以就的讲一下如何编写一个简单的who命令。

PPT

Manual Page

Manual Page 也就是大家常用的man命令,是unix、类unix系统常用的程序文档。1

2

3

4Usage:

$ man

$ man -k [apropos options] regexp

这种形式我们可以通过关键字来匹配手册中的descriptions。

man man:1 Executable programs or shell commands

2 System calls (functions provided by the kernel)

3 Library calls (functions within program libraries)

4 Special files (usually found in /dev)

5 File formats and conventions eg /etc/passwd

6 Games

7 Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7)

8 System administration commands (usually only for root)

9 Kernel routines [Non standard]

可以看出来我们主要用2 和 3

WHO1

2

3

4$ who

kcilcarus tty1 2018-07-06 06:06 (:0)

用户名 终端 时间

who命令对应的输出如上所示,那么我们猜下who的工作原理:用户登录登出的时候,会将信息保存在某个文件

who命令打开这个文件

读取文件信息

输入到控制台

恩, 逻辑很清晰。 下面就是如何做了。

如何知道who命令读取的那个文件呢?1

2

3

4

5

6

7

8

9

10

11

12$ man who

use /var/run/utmp

注意到这句话,

$ man -k utmp

utmp (5) - login records

$ man 5 utmp

The utmp file allows one to discover information about who is currently using the system.

那肯定是他了,而且还提供了相应的结构体信息,当然我们也可以在/usr/include/下面找到标准头文件

到这里我们知道了只要读取utmp文件就可以了。那么如何读取文件信息呢?

很自然我们想到了 man -k file, 只要知道了用哪个命令就好了, 当然也可以google1

2

3

4

5

6

7

8$ man -k file | grep read

read (2) - read from a file descriptor

其中这一行引起了我们的注意。哈哈 皮卡丘就是你了。

$ man 2 read

ssize_t read(int fd, void *buf, size_t count);

文件描述符 缓冲区 字节数

通过阅读文档, 我们了解到read有3个参数,返回值是成功读取的字节数并讲读取的字节存入缓冲区。

那应该就是他了,但是文件描述符又是什么鬼?

我们继续往下看,在see also 里 我们看到有个open(2)1

2

3

4$ man 2 open

int open(const char *pathname, int flags);

路径 进入模式: 只读,只写,读写

返回值是文件描述符。

那么,整理一下。open 打开文件, 返回文件描述符

read 根据文件描述符,读取文件内容,一次读取struct utmp 大小即可

输出到控制台

close 关闭文件1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35#include

#include

#include

#include

void (struct utmp * record);

int main()

{

struct utmp current_record;

int fd;

int len = sizeof(current_record);

if ((fd = open("/var/run/utmp", O_RDONLY)) == -1)

{

perror("/var/run/utmp");

exit(1);

}

while (read(fd, &current_record, len) == len)

{

show_record(&current_record);

}

close(fd);

exit(0);

}

void (struct utmp * record)

{

printf("%8s ", record->ut_user);

printf("%8s", record->ut_line);

printf("n");

}

恩 我们执行一下,1

2

3

4$ gcc test.c -o test

$ ./test

reboot ~

kcilcarus tty1

基本上可以了,不过reboot是啥,时间也没有,有空了在优化下。

那么,一个简单的who命令就到此结束啦~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值