linux學習之who命令學習

     在linux中,who用於顯示用戶相關的信息,該信息包含在結構體utmp中,包含用戶名,用戶的登錄時間等相關信息。

     在編寫who命令的c語言實現中,需要注意時間的顯示格式,使用ctime獲取時間的一般格式;

     其具體代碼如下:

    

//實現who功能函數
void whoread()
{
	struct utmp current_utmp;//用戶相關的結構體
	int len=sizeof(current_utmp);
	int utmpfd;
	if((utmpfd=open(UTMP_FILE,O_RDONLY))==-1)
			{
		     printf("error\n");
		     return;
			}
	while(read(utmpfd,¤t_utmp,len)==len) //讀取結構體
	{
		if(current_utmp.ut_type==USER_PROCESS)
			continue;
		printf("%-8.8s",current_utmp.ut_user);//用戶名
		printf(" ");
		printf("%-8.8s",current_utmp.ut_line);
		printf(" ");
		char *cp;
		cp=ctime(¤t_utmp.ut_tv);//登錄時間
		printf("%12.12s",cp+4);
		printf(" ");
#ifdef SHOWHOST
		printf("%-8.8s",current_utmp.ut_host);// the host
#endif
		printf("\n");
	}
	close(utmpfd);
	return ;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章