who.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* vi: set sw=4 ts=4: */
  2. /*----------------------------------------------------------------------
  3. * Mini who is used to display user name, login time,
  4. * idle time and host name.
  5. *
  6. * Author: Da Chen <dchen@ayrnetworks.com>
  7. *
  8. * This is a free document; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License
  10. * as published by the Free Software Foundation:
  11. * http://www.gnu.org/copyleft/gpl.html
  12. *
  13. * Copyright (c) 2002 AYR Networks, Inc.
  14. *----------------------------------------------------------------------
  15. */
  16. #include <sys/types.h>
  17. #include <fcntl.h>
  18. #include <unistd.h>
  19. #include <stdlib.h>
  20. #include <utmp.h>
  21. #include <sys/stat.h>
  22. #include <errno.h>
  23. #include <string.h>
  24. #include <time.h>
  25. #include "busybox.h"
  26. extern int who_main(int argc, char **argv)
  27. {
  28. struct utmp *ut;
  29. struct stat st;
  30. int devlen, len;
  31. time_t now, idle;
  32. if (argc > 1)
  33. bb_show_usage();
  34. setutent();
  35. devlen = sizeof("/dev/") - 1;
  36. printf("USER TTY IDLE FROM HOST\n");
  37. while ((ut = getutent()) != NULL) {
  38. char name[40];
  39. if (ut->ut_user[0] && ut->ut_type == USER_PROCESS) {
  40. len = strlen(ut->ut_line);
  41. if (ut->ut_line[0] == '/') {
  42. strncpy(name, ut->ut_line, len);
  43. name[len] = '\0';
  44. strcpy(ut->ut_line, ut->ut_line + devlen);
  45. } else {
  46. strcpy(name, "/dev/");
  47. strncpy(name+devlen, ut->ut_line, len);
  48. name[devlen+len] = '\0';
  49. }
  50. printf("%-10s %-8s ", ut->ut_user, ut->ut_line);
  51. if (stat(name, &st) == 0) {
  52. now = time(NULL);
  53. idle = now - st.st_atime;
  54. if (idle < 60)
  55. printf("00:00m ");
  56. else if (idle < (60 * 60))
  57. printf("00:%02dm ", (int)(idle / 60));
  58. else if (idle < (24 * 60 * 60))
  59. printf("%02d:%02dm ", (int)(idle / (60 * 60)),
  60. (int)(idle % (60 * 60)) / 60);
  61. else if (idle < (24 * 60 * 60 * 365))
  62. printf("%03ddays ", (int)(idle / (24 * 60 * 60)));
  63. else
  64. printf("%02dyears ", (int) (idle / (24 * 60 * 60 * 365)));
  65. } else
  66. printf("%-8s ", "?");
  67. printf("%-12.12s %s\n", ctime((time_t*)&(ut->ut_tv.tv_sec)) + 4, ut->ut_host);
  68. }
  69. }
  70. endutent();
  71. return 0;
  72. }