新聞中心
怎么用C語言實現(xiàn)linux的命令
命令是查詢當前登錄的每個用戶,它的輸出包括用戶名、終端類型、登錄日期及遠程主機,在Linux系統(tǒng)中輸入who命令輸出如下:

創(chuàng)新互聯(lián)是一家專注于網站設計、成都網站建設與策劃設計,湖口網站建設哪家好?創(chuàng)新互聯(lián)做網站,專注于網站建設10余年,網設計領域的專業(yè)建站公司;建站業(yè)務涵蓋:湖口等地區(qū)。湖口做網站價格咨詢:18982081108
我們先man一下who,在幫助文檔里可以看到,who命令是讀取/var/run/utmp文件來得到以上信息的。
我們再man一下utmp,知道utmp這個文件,是二進制文件,里面保存的是結構體數組,這些數組是struct utmp結構體的。
struct utmp {
short ut_type;
pid_t ut_pid;
char ut_line[UT_LINESIZE];
char ut_id[4];
char ut_user[UT_NAMESIZE];
char ut_host[UT_HOSTSIZE];
struct {
int32_t tv_sec;
int32_t tv_usec;
} ut_tv;
/***等等***/
};
要實現(xiàn)who只需要把utmp文件的所有結構體掃描過一遍,把需要的信息顯示出來就可以了,我們需要的信息有ut_user、ut_line、ut_tv、ut_host。
老師給的初始代碼:who1.c運行結果如下:
需要注意的是utmp中所保存的時間是以秒和微妙來計算的,所以我們需要把這個時間轉換為我們能看懂的時間,利用命令man -k time | grep 3搜索C語言中和時間相關的函數:
經過搜索發(fā)現(xiàn)了一個ctime()函數,似乎可以滿足我們的需求,于是對代碼中關于時間的printf進行修改:
printf("%s",ctime(utbufp-ut_time));
編譯運行發(fā)現(xiàn)出來的結果雖然已經轉換成了我們能看懂的時間格式,但是很明顯這個時間是錯的:
搜索一下ut_time這個宏,發(fā)現(xiàn)它被定義為int32_t類型:
但是ctime()函數中要求參數的類型是time_t類型,所以重新定義一下類型,編譯運行之后,發(fā)現(xiàn)時間已經改成了正確的,但是發(fā)現(xiàn)()中的內容被換行了,猜想ctime()函數的返回值可能自動在最后補了一個字符\n:
一開始想通過\r\b來實現(xiàn)“退行”,但實踐后發(fā)現(xiàn)并不可取,最后考慮到直接修改字符串中最后一個字符為\0,讓其字符串結束,使輸出達到與系統(tǒng)who命令一樣的效果,即在輸出語句前添加如下代碼:
cp[strlen(cp)-1] = '\0'
最后編譯執(zhí)行效果,發(fā)現(xiàn)解決了該問題:
雖然能看出基本上和who指令的執(zhí)行結果一致,但是并非完全一樣,主要在兩點,第一是時間格式不一樣,第二個是比who執(zhí)行的結果多了幾條,需要注意的是utmp中保存的用戶,不僅僅是已經登陸的用戶,還有系統(tǒng)的其他服務所需要的“用戶”,所以在顯出所有登陸用戶的時候,應該過濾掉其他用戶,只保留登陸用戶。我們可以通過ut_type來區(qū)別,登陸用戶的ut_type是USER_PROCESS。
先用if語句對執(zhí)行結果進行過濾,效果如下:
接著解決時間格式問題,利用man命令收到了兩個非常有用的函數:localtime()和strftime(),localtime()是把從1970-1-1零點零分到當前時間系統(tǒng)所偏移的秒數時間轉換為本地時間,strftime()則是用來定義時間格式的,如:年-月-日,利用這兩個函數對時間進行修改后,結果顯示終于和系統(tǒng)中who命令一模一樣:
最終完整的代碼如下:
#include stdio.h
#include stdlib.h
#include utmp.h
#include fcntl.h
#include unistd.h
#include time.h
#define SHOWHOST
void show_time(long timeval){
char format_time[40];
struct tm *cp;
cp = localtime(timeval);
strftime(format_time,40,"%F %R",cp);
printf("%s",format_time);
}
int show_info( struct utmp *utbufp )
{
if(utbufp-ut_type == USER_PROCESS){
printf("%-8.8s", utbufp-ut_name);
printf(" ");
printf("%-8.8s", utbufp-ut_line);
printf(" ");
show_time(utbufp-ut_time);
printf(" ");
#ifdef SHOWHOST
printf("(%s)", utbufp-ut_host);
#endif
printf("\n");
}
return 0;
}
int main()
{
struct utmp current_record;
int utmpfd;
int reclen = sizeof(current_record);
if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){
perror( UTMP_FILE );
exit(1);
}
while ( read(utmpfd, current_record, reclen) == reclen )
show_info(current_record);
close(utmpfd);
return 0;
}
怎樣用c語言使linux系統(tǒng)關機
把system里邊的命令改成"shutdown -r now"看看....
沒Linux系統(tǒng),無法測試
寫一個linux下寫個關于c語言的雙守護進程,就是監(jiān)視一個進程,當其死掉,馬上將其重啟
可以分三步來做:
做兩個簡單的守護進程,并能正常運行
監(jiān)控進程是否在運行
啟動進程
綜合起來就可以了,代碼如下:
被監(jiān)控進程thisisatest.c(來自):
#includeunistd.h
#includesignal.h
#includestdio.h
#includestdlib.h
#includesys/param.h
#includesys/types.h
#includesys/stat.h
#includetime.h
void init_daemon()
{
int pid;
int i;
pid=fork();
if(pid0) ?
exit(1); ?//創(chuàng)建錯誤,退出
else if(pid0) //父進程退出
exit(0);
setsid(); //使子進程成為組長
pid=fork();
if(pid0)
exit(0); //再次退出,使進程不是組長,這樣進程就不會打開控制終端
else if(pid0) ?
exit(1);
//關閉進程打開的文件句柄
for(i=0;iNOFILE;i++)
close(i);
chdir("/root/test"); ?//改變目錄
umask(0);//重設文件創(chuàng)建的掩碼
return;
}
void main()
{
FILE *fp;
time_t t;
init_daemon();
while(1)
{
? sleep(60); //等待一分鐘再寫入
? fp=fopen("testfork2.log","a");
? if(fp=0)
? {
? ? ? time(t);
? ? ? fprintf(fp,"current time is:%s\n",asctime(localtime(t))); ?//轉換為本地時間輸出
? ? ? fclose(fp);
? }
}
return;
}
監(jiān)控進程monitor.c:
#includeunistd.h
#includesignal.h
#includestdio.h
#includestdlib.h
#includesys/param.h
#includesys/types.h
#includesys/stat.h
#includetime.h
#includesys/wait.h
#includefcntl.h
#includelimits.h
#define BUFSZ 150
void init_daemon()
{
int pid;
int i;
pid=fork();
if(pid0)
exit(1); ?//創(chuàng)建錯誤,退出
else if(pid0) //父進程退出
exit(0);
setsid(); //使子進程成為組長
pid=fork();
if(pid0)
exit(0); //再次退出,使進程不是組長,這樣進程就不會打開控制終端
else if(pid0)
exit(1);
//關閉進程打開的文件句柄
for(i=0;iNOFILE;i++)
close(i);
chdir("/root/test"); ?//改變目錄
umask(0);//重設文件創(chuàng)建的掩碼
return;
}
void err_quit(char *msg)
{
perror(msg);
exit(EXIT_FAILURE);
}
// 判斷程序是否在運行
int does_service_work()
{
FILE* fp;
int count;
char buf[BUFSZ];
char command[150];
sprintf(command, "ps -ef | grep thisisatest | grep -v grep | wc -l" );
if((fp = popen(command,"r")) == NULL)
err_quit("popen");
if( (fgets(buf,BUFSZ,fp))!= NULL )
{
count = atoi(buf);
}
pclose(fp);
return count;
// exit(EXIT_SUCCESS);
}
void main()
{
FILE *fp;
time_t t;
int count;
init_daemon();
while(1)
{
? sleep(10); //等待一分鐘再寫入
? fp=fopen("testfork3.log","a");
? if(fp=0)
? {
? ? ? count = does_service_work();
? ? ? time(t);
? ? ? if(count0)
? ? ? ? ? fprintf(fp,"current time is:%s and the process exists, the count is %d\n",asctime(localtime(t)), count); ?//轉換為本地時間輸出
? ? ? else
? ? ? {
? ? ? ? ? fprintf(fp,"current time is:%s and the process does not exist, restart it!\n",asctime(localtime(t))); ?//轉換為本地時間輸出
? ? ? ? ? system("/home/user/daemon/thisisatest"); //啟動服務
? ? ? }
? ? ? fclose(fp);
? }
}
return;
}
具體CMD命令:
cc thisisatest.c -o thisisatest
./thisisatest
cc monitor.c -o monitor
./monitor
tail -f testfork3.log ? -- 查看日志
c語言中 重啟電腦的命令是什么
重啟:shutdown -r
關機:shutdown -h
其他命令參數如下。
Usage: shutdown [-i | -l | -s | -r | -a] [-f] [-m \\computername] [-t xx] [-c "c
omment"] [-d up:xx:yy]
No args Display this message (same as -?)
-i Display GUI interface, must be the first option
-l Log off (cannot be used with -m option)
-s Shutdown the computer
-r Shutdown and restart the computer
-a Abort a system shutdown
-m \\computername Remote computer to shutdown/restart/abort
-t xx Set timeout for shutdown to xx seconds
-c "comment" Shutdown comment (maximum of 127 characters)
-f Forces running applications to close without war
ning
-d [u][p]:xx:yy The reason code for the shutdown
u is the user code
p is a planned shutdown code
xx is the major reason code (positive integer le
ss than 256)
yy is the minor reason code (positive integer le
ss than 65536)
分享題目:c語言重啟命令linux c++重啟程序
網頁URL:http://www.dlmjj.cn/article/hhsdch.html


咨詢
建站咨詢
