who.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  16. *
  17. *----------------------------------------------------------------------
  18. */
  19. #include "libbb.h"
  20. #include <utmp.h>
  21. #include <time.h>
  22. static void idle_string(char *str6, time_t t)
  23. {
  24. t = time(NULL) - t;
  25. /*if (t < 60) {
  26. str6[0] = '.';
  27. str6[1] = '\0';
  28. return;
  29. }*/
  30. if (t >= 0 && t < (24 * 60 * 60)) {
  31. sprintf(str6, "%02d:%02d",
  32. (int) (t / (60 * 60)),
  33. (int) ((t % (60 * 60)) / 60));
  34. return;
  35. }
  36. strcpy(str6, "old");
  37. }
  38. int who_main(int argc, char **argv);
  39. int who_main(int argc, char **argv)
  40. {
  41. char str6[6];
  42. struct utmp *ut;
  43. struct stat st;
  44. char *name;
  45. if (argc > 1) {
  46. bb_show_usage();
  47. }
  48. setutent();
  49. printf("USER TTY IDLE TIME HOST\n");
  50. while ((ut = getutent()) != NULL) {
  51. if (ut->ut_user[0] && ut->ut_type == USER_PROCESS) {
  52. time_t thyme = ut->ut_tv.tv_sec;
  53. /* ut->ut_line is device name of tty - "/dev/" */
  54. name = concat_path_file("/dev", ut->ut_line);
  55. str6[0] = '?';
  56. str6[1] = '\0';
  57. if (stat(name, &st) == 0)
  58. idle_string(str6, st.st_atime);
  59. printf("%-10s %-8s %-9s %-14.14s %s\n",
  60. ut->ut_user, ut->ut_line, str6,
  61. ctime(&thyme) + 4, ut->ut_host);
  62. if (ENABLE_FEATURE_CLEAN_UP)
  63. free(name);
  64. }
  65. }
  66. if (ENABLE_FEATURE_CLEAN_UP)
  67. endutent();
  68. return 0;
  69. }