1
0

who2.c.1 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* who2.c - read /etc/utmp and list info therein
  2. * - suppresses empty records
  3. * - formats time nicely
  4. */
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include <utmp.h>
  8. #include <fcntl.h>
  9. #include <time.h>
  10. /* #define SHOWHOST */
  11. void showtime(long);
  12. void show_info(struct utmp *);
  13. int main()
  14. {
  15. struct utmp utbuf; /* read info into here */
  16. int utmpfd; /* read from this descriptor */
  17. if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){
  18. perror(UTMP_FILE);
  19. exit(1);
  20. }
  21. while( read(utmpfd, &utbuf, sizeof(utbuf)) == sizeof(utbuf) )
  22. show_info( &utbuf );
  23. close(utmpfd);
  24. return 0;
  25. }
  26. /*
  27. * show info()
  28. * displays the contents of the utmp struct
  29. * in human readable form
  30. * * displays nothing if record has no user name
  31. */
  32. void show_info( struct utmp *utbufp )
  33. {
  34. if ( utbufp->ut_type != USER_PROCESS )
  35. return;
  36. printf("%-8.8s", utbufp->ut_name); /* the logname */
  37. printf(" "); /* a space */
  38. printf("%-8.8s", utbufp->ut_line); /* the tty */
  39. printf(" "); /* a space */
  40. showtime( utbufp->ut_time ); /* display time */
  41. #ifdef SHOWHOST
  42. if ( utbufp->ut_host[0] != '\0' )
  43. printf(" (%s)", utbufp->ut_host);/* the host */
  44. #endif
  45. printf("\n"); /* newline */
  46. }
  47. void showtime( long timeval )
  48. /*
  49. * displays time in a format fit for human consumption
  50. * uses ctime to build a string then picks parts out of it
  51. * Note: %12.12s prints a string 12 chars wide and LIMITS
  52. * it to 12chars.
  53. */
  54. {
  55. char *cp; /* to hold address of time */
  56. cp = ctime(&timeval); /* convert time to string */
  57. /* string looks like */
  58. /* Mon Feb 4 00:46:40 EST 1991 */
  59. /* 0123456789012345. */
  60. printf("%12.12s", cp+4 ); /* pick 12 chars from pos 4 */
  61. }