用系統呼叫實現who命令 mywho

2022-06-19 20:45:15 字數 2826 閱讀 9315

使用man who檢視詳細內容

可以看到,who命令用於顯示目前登入系統的使用者資訊。

輸入man -k utmp,可以看到

輸入man utmp,可以看到utmp的結構

struct utmp  ut_tv;                      /* time entry was made */

#else

long ut_session; /* session id */

struct timeval ut_tv; /* time entry was made */

#endif

int32_t ut_addr_v6[4]; /* internet address of remote

host; ipv4 address uses

just ut_addr_v6[0] */

char __unused[20]; /* reserved for future use */

};

這是utmp結構體的定義,從注釋中可以了解到:ut_line儲存裝置名,即使用者的終端型別;ut_user儲存登入名;ut_host儲存使用者用於登入的遠端計算機的名字;使用者的登入時間被儲存在ut_tv結構體中。

who的原理便是讀取/var/run/utmp部分檔案內容,輸出到螢幕。

#include #include #include #include #include #include #define showost

void showinfo(struct utmp *utbufp);

long showtime(long timeval);

int main()

while (read(utmpfd,¤t_record,reclen)==reclen)

showinfo(¤t_record);

close(utmpfd);

return 0;

}void showinfo(struct utmp *utbufp)

}long showtime(long timeval)

45,1 底端

main函式使用系統呼叫open,read,close對utmp檔案進行操作

用來儲存資料的結構體中資料不斷讀出,但是在utmp中,系統對每種使用者都給了標示符:

#define empty         0 /* record does not contain valid info (formerly known as ut_unknown on linux) */

#define run_lvl 1 /* change in system run-level (seeinit(8)) */

#define boot_time 2 /* time of system boot (in ut_tv) */

#define new_time 3 /* time after system clock change (in ut_tv) */

#define old_time 4 /* time before system clock change (in ut_tv) */

#define init_process 5 /* process spawned by init(8) */

#define login_process 6 /* session leader process for user login */

#define user_process 7 /* normal process */

#define dead_process 8 /* terminated process */

#define accounting 9 /* not implemented */

而我們需要列印的是識別符號為7的user_process

我呼叫了標頭檔案time.h,其中的儲存時間的結構體內容如下所示:

utbufp->ut_time是乙個時間資料,其儲存的是從2023年1月1日0:00開始到現在所經過的秒數。

通過gmtime可以將這個資料轉換為結構體tm。

但是需要注意的是tm結構體中tm_year年份數值是減去了2023年,所以輸出時需要加上1900。

Linux命令實現(1) who

想學linux c程式設計 借來的書都千篇一律 都是從讀寫檔案到程序通訊和socket 感覺沒有vc的書豐富 學起來也很枯燥 終於借到一本帶例項的書 understanding unix linux programming a guide to theroy and practice 一本在例項裡教...

Linux下who命令的實現

linux系統的正常運作需要使用大量與系統有關的資料檔案,例如,口令檔案 etc passwd和組檔案 etc group就是經常被多個程式頻繁使用的兩個檔案。使用者每次登陸 linux系統,以及每次執行ls l命令時都要使用口令檔案。本實驗中的程式就是這樣乙個需要呼叫系統資料檔案的程式,只不過呼叫...

系統呼叫實現Linux命令 cp

和命令ls一樣,我以前在網易上寫的搬過來,嘻嘻!cp.c如下 include cp.h 注意 計算完檔案大小後 要記得指標復位 記得關閉檔案 void cp char src path filename,char dest path filename 以唯讀方式開啟原始檔 int fd src op...