[cpp] #include
#include
#include
#include
#include
#include
void show_info(struct utmp *);
void showtime(long);
int main()
{
int fd;
struct utmp current_record;
int reclen = sizeof(struct utmp);
/* UTMP_FILE就是/var/run/utmp.在/usr/include/paths.h下 */
fd = open(UTMP_FILE, O_RDONLY);
if (fd == -1)
{
perror(UTMP_FILE);
exit(1);
}
while (read(fd, ¤t_record, reclen))
show_info(¤t_record);
close(fd);
return 0;
}
/* displays the contents of the utmp struct, display nothing if utmp has no user name */
void show_info(struct utmp *utbufp)
{
if (utbufp->ut_type != USER_PROCESS)
return;
printf("%-8.8s", utbufp->ut_user); /* The user name */
printf(" ");
printf("%-8.8s", utbufp->ut_line); /* The tty name */
printf(" ");
showtime(utbufp->ut_time); /* utime */
#ifdef SHOWHOST
if (utbufp->ut_host[0] != '\0')
printf(" (%s)", utbufp->ut_host); /* the host */
#endif
printf("\n");
}
/* displays time in a format */
void showtime(long timeva l)
{
char *cp;
cp = ctime(&timeva l); /* convert time to string */
printf("%20.20s", cp+4); /* %12.12s prints a string 20 chars wide and LIMITS it to 20 chars. cp+4是为了把最前面的星期去掉 */
}
#include
#include
#include
#include
#include
#include
void show_info(struct utmp *);
void showtime(long);
int main()
{
int fd;
struct utmp current_record;
int reclen = sizeof(struct utmp);
/* UTMP_FILE就是/var/run/utmp.在/usr/include/paths.h下 */
fd = open(UTMP_FILE, O_RDONLY);
if (fd == -1)
{
perror(UTMP_FILE);
exit(1);
}
while (read(fd, ¤t_record, reclen))
show_info(¤t_record);
close(fd);
return 0;
}
/* displays the contents of the utmp struct, display nothing if utmp has no user name */
void show_info(struct utmp *utbufp)
{
if (utbufp->ut_type != USER_PROCESS)
return;
printf("%-8.8s", utbufp->ut_user); /* The user name */
printf(" ");
printf("%-8.8s", utbufp->ut_line); /* The tty name */
printf(" ");
showtime(utbufp->ut_time); /* utime */
#ifdef SHOWHOST
if (utbufp->ut_host[0] != '\0')
printf(" (%s)", utbufp->ut_host); /* the host */
#endif
printf("\n");
}
/* displays time in a format */
void showtime(long timeva l)
{
char *cp;
cp = ctime(&timeva l); /* convert time to string */
printf("%20.20s", cp+4); /* %12.12s prints a string 20 chars wide and LIMITS it to 20 chars. cp+4是为了把最前面的星期去掉 */
}
增加了缓冲机制的who命令实现:这样会减少read()函数调用的次数,提高程序效率和性能。
主函数为:who1.c
[cpp] #include
#include
#include
#include
#include
#include
#include /* 包含实现缓冲的文件 */
void show_info(struct utmp *);
void showtime(long);
int main()
{
int fd;
struct utmp *utbufp;
int reclen = sizeof(struct utmp);
/* UTMP_FILE就是/var/run/utmp.在/usr/include/paths.h下 */
if (utmp_open(UTMP_FILE) == -1)
{
perror(UTMP_FILE);
exit(1);
}
while((utbufp = utmp_next()) != ((struct utmp *)NULL))
show_info(utbufp);
utmp_close();
return 0;
}
/* displays the contents of the utmp struct, display nothing if utmp has no user name */
void show_info(struct utmp *utbufp)
{
if (utbufp->ut_type != USER_PROCESS)
return;
printf("%-8.8s"