linux命令编写,编写简单的linux命令
8種機(jī)械鍵盤(pán)軸體對(duì)比
本人程序員,要買一個(gè)寫(xiě)代碼的鍵盤(pán),請(qǐng)問(wèn)紅軸和茶軸怎么選?
又到了周四分享環(huán)節(jié),鑒于最近在看linux編程實(shí)踐,所以就的講一下如何編寫(xiě)一個(gè)簡(jiǎn)單的who命令。
PPT
Manual Page
Manual Page 也就是大家常用的man命令,是unix、類unix系統(tǒng)常用的程序文檔。1
2
3
4Usage:
$ man
$ man -k [apropos options] regexp
這種形式我們可以通過(guò)關(guān)鍵字來(lái)匹配手冊(cè)中的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]
可以看出來(lái)我們主要用2 和 3
WHO1
2
3
4$ who
kcilcarus tty1 2018-07-06 06:06 (:0)
用戶名 終端 時(shí)間
who命令對(duì)應(yīng)的輸出如上所示,那么我們猜下who的工作原理:用戶登錄登出的時(shí)候,會(huì)將信息保存在某個(gè)文件
who命令打開(kāi)這個(gè)文件
讀取文件信息
輸入到控制臺(tái)
恩, 邏輯很清晰。 下面就是如何做了。
如何知道who命令讀取的那個(gè)文件呢?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.
那肯定是他了,而且還提供了相應(yīng)的結(jié)構(gòu)體信息,當(dāng)然我們也可以在/usr/include/下面找到標(biāo)準(zhǔn)頭文件
到這里我們知道了只要讀取utmp文件就可以了。那么如何讀取文件信息呢?
很自然我們想到了 man -k file, 只要知道了用哪個(gè)命令就好了, 當(dāng)然也可以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);
文件描述符 緩沖區(qū) 字節(jié)數(shù)
通過(guò)閱讀文檔, 我們了解到read有3個(gè)參數(shù),返回值是成功讀取的字節(jié)數(shù)并講讀取的字節(jié)存入緩沖區(qū)。
那應(yīng)該就是他了,但是文件描述符又是什么鬼?
我們繼續(xù)往下看,在see also 里 我們看到有個(gè)open(2)1
2
3
4$ man 2 open
int open(const char *pathname, int flags);
路徑 進(jìn)入模式: 只讀,只寫(xiě),讀寫(xiě)
返回值是文件描述符。
那么,整理一下。open 打開(kāi)文件, 返回文件描述符
read 根據(jù)文件描述符,讀取文件內(nèi)容,一次讀取struct utmp 大小即可
輸出到控制臺(tái)
close 關(guān)閉文件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");
}
恩 我們執(zhí)行一下,1
2
3
4$ gcc test.c -o test
$ ./test
reboot ~
kcilcarus tty1
基本上可以了,不過(guò)reboot是啥,時(shí)間也沒(méi)有,有空了在優(yōu)化下。
那么,一個(gè)簡(jiǎn)單的who命令就到此結(jié)束啦~
總結(jié)
以上是生活随笔為你收集整理的linux命令编写,编写简单的linux命令的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: 第二章《蜂群思维》
- 下一篇: 大数据技术原理与应用(第三版)林子雨教材
