系统:ubuntu 12.04
1.man who
有这么几句话:
If FILE is not specified, use /var/run/utmp. /var/log/wtmp as FILE is
common. If ARG1 ARG2 given, -m presumed: `am i' or `mom likes' are
usual.
who命令索取信息存在这个文档中
2.看到关键词utmp wtmp
man -k utmp
挑选后的结果
utmp (5) - login records
3.察看utmp的帮助文档
man 5 utmp
里面有utmp数据结构的详细说明
4.将文件中utmp中的信息读取出来
用 open read close 函数
5.在我的struct utmp 中没有ut_time 的直接定义
# define ut_time ut_tv.tv_sec
struct
{
int32_t tv_sec; /* Seconds. */ //时间的秒数
int32_t tv_usec; /* Microseconds. */
} ut_tv;
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <utmp.h>
#include <fcntl.h>
#include <time.h>
#define SHOWHOST //decide to show host or not
void showtime(long);
void show_info(struct utmp *);
int main()
{
struct utmp utbuf; /* read info into here */
int utmpfd; /* read from this descriptor */
if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){
perror(UTMP_FILE); //perror()
exit(1);
}
while( read(utmpfd, &utbuf, sizeof(utbuf)) == sizeof(utbuf) )
show_info( &utbuf );
close(utmpfd);
return 0;
}
void show_info( struct utmp *utbufp )
{
if ( utbufp->ut_type != USER_PROCESS ) //dont show no useful infomation
return;
printf("%-8.8s", utbufp->ut_name); /* the logname */
printf(" "); /* a space */
printf("%-8.8s", utbufp->ut_line); /* the tty */
printf(" "); /* a space */
showtime( utbufp->ut_time ); /* display time */
#ifdef SHOWHOST
if ( utbufp->ut_host[0] != '\0' )
printf(" (%s)", utbufp->ut_host);/* the host */
#endif
printf("\n"); /* newline */
}
void showtime( long timeval )
/*
* displays time in a format fit for human consumption
* uses ctime to build a string then picks parts out of it
* Note: %12.12s prints a string 12 chars wide and LIMITS
* it to 12chars.
*/
{
char *cp; /* to hold address of time */
cp = ctime(&timeval); /* convert time to string */
/* string looks like */
/* Mon Feb 4 00:46:40 EST 1991 */
/* 0123456789012345. */
printf("%12.12s", cp+4 ); /* pick 12 chars from pos 4 */
}
2463

被折叠的 条评论
为什么被折叠?



