编写who命令

来源:互联网 发布:thinkphp nginx 配置 编辑:程序博客网 时间:2024/04/30 05:37

命令也是程序:

在unix系统中,几乎所有的命令都是人文编写的程序,如who和ls,而且他们大多数都是都是用c编写的。在unix系统中增加新的命令是一件很容易的事情,把程序的可执行文件放到以下任意一个目录就可以了:/bin,/usr/bin,/usr/local/bin。

打开utmp文件:

#include<stdio.h>#include<fcntl.h>#include<unistd.h>#include<utmp.h>void main(){    int fd;    fd=open(UTMP_FILE,O_RDONLY);    if(fd!=-1)    {        printf("ok!");    }    close(fd);}

程序:

#include<stdio.h>#include<fcntl.h>#include<unistd.h>#include<utmp.h>#include<time.h>void show_info(struct utmp *);void showtime(long);void main(){struct utmp current_record;int utmpfd;int reclen=sizeof(current_record);utmpfd=open(UTMP_FILE,O_RDONLY);if(utmpfd==-1){perror(UTMP_FILE);}while(read(utmpfd,&t_record,reclen)==reclen)show_info(&t_record);close(utmpfd);}void show_info(struct utmp *utmp){if(utmp->ut_type!=USER_PROCESS)return;printf("%-8.8s",utmp->ut_name);printf("\t");printf("%-8.8s",utmp->ut_line);printf("\t");showtime(utmp->ut_time);printf("\t");#ifdef SHOWHOSTprintf("%s",utmp->ut_host);#endifprintf("\n");}void showtime(long timeval){char *cp;cp=ctime(&timeval);printf("%12.12s",cp+4);}














0 0
原创粉丝点击