用系统调用实现who命令mywho

用系统调用实现who命令

查看who命令的功能

输入man who查看详细功能

源代码:

点击查看代码
#include <stdio.h>
#include <stdlib.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#define SHOWOST
void showinfo(struct utmp *utbufp);
long showtime(long timeval);
int main()
{
        struct utmp current_record;
        int utmpfd;
        int reclen = sizeof(current_record);
        if((utmpfd = open(UTMP_FILE,O_RDONLY))==-1)
        {
                perror(UTMP_FILE);
                exit(1);
        }
        while (read(utmpfd,&current_record,reclen)==reclen)
                showinfo(&current_record);
        close(utmpfd);
        return 0;
}
void showinfo(struct utmp *utbufp){
        if(utbufp->ut_type!=USER_PROCESS)
                return;
        else{
                printf("%-8.8s",utbufp->ut_name);
                printf(" ");
                printf("%-8.8s",utbufp->ut_line);
                printf(" ");
                showtime(utbufp->ut_time);
                printf(" ");
                printf("(%s)",utbufp->ut_host);
                printf("\n");
        }
}
long showtime(long timeval)
{
        struct tm *cp;
        cp = gmtime(&timeval);
        printf("    ");
        printf("%d-%d-%d %d:%d ",cp->tm_year+1900,cp->tm_mon+1,cp->tm_mday,(cp->tm_hour+8)%24,cp->tm_min);
}

码云链接:

mywho.c · 魏赫/C语言实现stat_ls_who命令 - 码云 - 开源中国 (gitee.com)

运行结果:

posted @ 2022-10-16 16:07  少管我  阅读(16)  评论(0编辑  收藏  举报