您的位置:首页 > 运维架构 > Linux

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

2014-01-13 13:19 316 查看
下面是简单实现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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: