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, ¤t_record, len) == len)
{
show_record(¤t_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命令就到此結束啦~