編寫who命令-第2版

之前寫過第1版who命令:
http://m.itdecent.cn/p/ac7dce45bd95

緩沖是提高文件I/O效率的方法之一,現(xiàn)在運用緩沖技術寫第2版who命令:
分為2個文件utmplib.c和who2.c,who2.c把前一個文件include進來即可。

下面是utmplib.c:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utmp.h>
#include <unistd.h>
#include <time.h>

#define UTMP_SIZE (sizeof(struct utmp))
#define NUM 3

int fd = -1;
int cur_utmp = 0;
int num_utmp = 0;
char utmpbuf[NUM * UTMP_SIZE];

void utmp_open(char *filename) {
    if((fd = open(filename, O_RDONLY)) == -1) {
        printf("Can't open file %s\n", filename);
        exit(1);
    }
}

int utmp_load() {
    int res = read(fd, utmpbuf, NUM * UTMP_SIZE);
    num_utmp = res/UTMP_SIZE;
    cur_utmp = 0;
    return num_utmp;
}

struct utmp * utmp_next() {
    if (cur_utmp == num_utmp && utmp_load() == 0) {
        return (struct utmp *)NULL;
    }
    return (struct utmp *)&utmpbuf[(cur_utmp++)*UTMP_SIZE];
}

void utmp_close() {
    if (fd != -1) {
        close(fd);
    }
}

void show_time(time_t t) {
    struct tm *tt = localtime(&t);
    printf("%d-%02d-%02d %02d:%02d", tt->tm_year+1900, tt->tm_mon+1, tt->tm_mday, tt->tm_hour, tt->tm_min);
}

void show_info(struct utmp *record) {
    if (record->ut_type != USER_PROCESS)
        return;
    printf("%-8s", record->ut_user);
    printf(" ");
    printf("%-12s", record->ut_line);
    printf(" ");
    show_time(record->ut_tv.tv_sec);
    printf(" ");
    printf("(%s)", record->ut_host);
    printf("\n");
}

下面是who2.c:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utmp.h>
#include <unistd.h>
#include <time.h>
#include "utmplib.c"

int main() {
    utmp_open("/var/run/utmp");
    struct utmp *utmp_record;
    while ((utmp_record=utmp_next()) != (struct utmp *)NULL) {
        show_info(utmp_record);
    }
    utmp_close();
    return 0;
}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容