who命令简单实现

1100阅读 0评论2014-04-18 do_my_heart
分类:C/C++


点击(此处)折叠或打开

  1. /*
  2.  *【带缓冲who命令简单实现】
  3.  *who:用来查看当前有哪些用户登录到了本台机器上。
  4.  *添加 whats_my_line支持who am i命令
  5.  */
  6. #include<stdio.h>
  7. #include<stdlib.h>
  8. #include<fcntl.h>
  9. #include<utmp.h>
  10. #include<time.h>

  11. #define    UTMP_SIZE    (sizeof(struct utmp))
  12. #define    UTMP_NRECS    16

  13. char utmp_buf[UTMP_NRECS*UTMP_SIZE];

  14. int cur_rec = 0;    //当前记录
  15. int num_recs = 0;    //记录个数

  16. struct utmp * utmp_next(int fd_utmp);
  17. int utmp_reload(int fd_utmp);

  18. char * whats_my_line(int fd);
  19. void show_info(struct utmp * utbuf_fp);


  20. int main(int argc,char *argv[])
  21. {
  22.     int fd_utmp;
  23.     char *my_line = NULL;
  24.     
  25.     if(argc == 3)                    //who am i情况
  26.         my_line = whats_my_line(0);
  27.         
  28.     if( (fd_utmp = open(UTMP_FILE,O_RDONLY)) == -1)
  29.     {
  30.         perror("open UTMP_FILE failed");
  31.         exit(1);
  32.     }
  33.     
  34.     struct utmp * utmp_p;
  35.     while( (utmp_p = utmp_next(fd_utmp)) != NULL)
  36.     {
  37.         if(my_line == NULL || strcmp(utmp_p->ut_line,my_line) == 0)
  38.             show_info(utmp_p);
  39.     }
  40.     
  41.     if(close(fd_utmp) == -1 )
  42.     {
  43.         perror("close file failed");
  44.         exit(1);
  45.     }
  46.     return 0;
  47. }

  48. struct utmp * utmp_next(int fd_utmp)
  49. {
  50.     if( (cur_rec == num_recs) && (utmp_reload(fd_utmp)==0) )    //缓冲区数据取完
  51.         return (struct utmp *)NULL;
  52.         
  53.     return (struct utmp *)&utmp_buf[cur_rec++ * UTMP_SIZE];        //下一个记录
  54. }

  55. int utmp_reload(int fd_utmp)
  56. {    //缓冲区数据读取完,重新放数据到缓冲区utmp_buf
  57.     cur_rec = num_recs = 0;
  58.     int bytes_r = read(fd_utmp,utmp_buf,UTMP_SIZE*UTMP_NRECS);
  59.     if(bytes_r == -1)
  60.     {
  61.         perror("read failed");
  62.         return 0;
  63.     }
  64.     num_recs = bytes_r / UTMP_SIZE;
  65.     
  66.     return num_recs;
  67. }

  68. char * whats_my_line(int fd)
  69. {    //获取当前终端名称
  70.     char * tty_name;
  71.     if( tty_name = ttyname(fd) )
  72.     {
  73.         printf("%s\n",tty_name);
  74.         if( strncmp("/dev/",tty_name,5) == 0 )
  75.             tty_name += 5;
  76.     }
  77.     return tty_name;
  78. }

  79. void show_info(struct utmp * utbuf_fp)
  80. {
  81.     if(utbuf_fp->ut_type != USER_PROCESS)//没有登录的用户
  82.         return;
  83.     printf("%-8.8s ",utbuf_fp->ut_name);
  84.     printf("%-8.8s ",utbuf_fp->ut_line);
  85.     printf("%s",ctime(&utbuf_fp->ut_time));//ctime转换后带\n
  86.     
  87. }
上一篇:more命令简单实现
下一篇:cp命令简单实现