linux编程实践3(实现who命令)

时间:2014-01-21 10:07:41   收藏:0   阅读:390

下面是简单实现linux下who命令的代码,主要就是从utmp这个文件中读取和用户登录相关的信息,并显示出来。

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<utmp.h>
#include<time.h>

void show_info(struct utmp *);
void show_time(long timeval);

int main(int argc, char **argv)
{
    struct utmp current_record;
    int read_len = sizeof(current_record);
    int fd;

    if((fd = open(UTMP_FILE, O_RDONLY)) == -1)
    {
        perror(UTMP_FILE);
        exit(1);
    }

    while(read(fd, ¤t_record, read_len) == read_len)
        show_info(¤t_record);
    close(fd);

    return 0;
}

void show_info(struct utmp *utmpbuf)
{
    if(utmpbuf->ut_type != USER_PROCESS)
        return;
    printf("%-8.8s", utmpbuf->ut_user);
    printf(" ");
    printf("%-8.8s", utmpbuf->ut_line);
    printf(" ");
    //printf("%10ld", utmpbuf->ut_time);
    show_time(utmpbuf->ut_time);
    printf(" ");
#ifdef SHOWHOST
    printf("(%s)", utmp->ut_host);
#endif
    printf("\n");
}

void show_time(long timeval)
{
    char *cp;
    cp = ctime(&timeval);
    printf("%12.12s", cp+4);
}


原文:http://blog.csdn.net/wangyiyan315/article/details/18219245

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!