1
0

who2.c 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. #include <string.h>
  11. /* #define SHOWHOST */
  12. void showtime(long);
  13. void show_info(struct utmp *);
  14. int main( int ac , char *av[] )
  15. {
  16. char arg2[] = "am";
  17. char arg3[] = "i";
  18. struct utmp utbuf; /* read info into here */
  19. int utmpfd; /* read from this descriptor */
  20. if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){
  21. perror(UTMP_FILE);
  22. exit(1);
  23. }
  24. if (ac == 1) {
  25. while( read(utmpfd, &utbuf, sizeof(utbuf)) == sizeof(utbuf) )
  26. show_info( &utbuf );
  27. }
  28. if ( ac > 1 ) {
  29. if ( ! strcmp (av[1], arg2 ) ) {
  30. if ( ! strcmp (av[2], arg3) ) {
  31. // user has typed "who am i"
  32. while( read(utmpfd, &utbuf, sizeof(utbuf)) == sizeof(utbuf) )
  33. // show_info( &utbuf );
  34. show_name ( &utbuf );
  35. }
  36. }
  37. }
  38. close(utmpfd);
  39. return 0;
  40. }
  41. void show_name( struct utmp *utbufp )
  42. {
  43. if ( utbufp->ut_type != USER_PROCESS )
  44. return;
  45. printf("%s\n", utbufp->ut_name); /* the logname */
  46. }
  47. /*
  48. * show info()
  49. * displays the contents of the utmp struct
  50. * in human readable form
  51. * * displays nothing if record has no user name
  52. */
  53. void show_info( struct utmp *utbufp )
  54. {
  55. if ( utbufp->ut_type != USER_PROCESS )
  56. return;
  57. printf("%-8.8s", utbufp->ut_name); /* the logname */
  58. printf(" "); /* a space */
  59. printf("%-8.8s", utbufp->ut_line); /* the tty */
  60. printf(" "); /* a space */
  61. showtime( utbufp->ut_time ); /* display time */
  62. #ifdef SHOWHOST
  63. if ( utbufp->ut_host[0] != '\0' )
  64. printf(" (%s)", utbufp->ut_host);/* the host */
  65. #endif
  66. printf("\n"); /* newline */
  67. }
  68. void showtime( long timeval )
  69. /*
  70. * displays time in a format fit for human consumption
  71. * uses ctime to build a string then picks parts out of it
  72. * Note: %12.12s prints a string 12 chars wide and LIMITS
  73. * it to 12chars.
  74. */
  75. {
  76. char *cp; /* to hold address of time */
  77. cp = ctime(&timeval); /* convert time to string */
  78. /* string looks like */
  79. /* Mon Feb 4 00:46:40 EST 1991 */
  80. /* 0123456789012345. */
  81. printf("%12.12s", cp+4 ); /* pick 12 chars from pos 4 */
  82. }