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

下面是简单实现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);
}


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

上一篇:kafka Failed to send messages after 3 tries 问题解决


下一篇:hdu 1956 || poj 1637 Sightseeing tour (混合图欧拉回路)