who.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 "busybox.h"
  20. #include <utmp.h>
  21. #include <time.h>
  22. static const char * idle_string (time_t t)
  23. {
  24. static char str[6];
  25. time_t s = time(NULL) - t;
  26. if (s < 60)
  27. return ".";
  28. if (s < (24 * 60 * 60)) {
  29. sprintf(str, "%02d:%02d",
  30. (int) (s / (60 * 60)),
  31. (int) ((s % (60 * 60)) / 60));
  32. return str;
  33. }
  34. return "old";
  35. }
  36. int who_main(int argc, char **argv)
  37. {
  38. struct utmp *ut;
  39. struct stat st;
  40. char *name;
  41. if (argc > 1) {
  42. bb_show_usage();
  43. }
  44. setutent();
  45. printf("USER TTY IDLE TIME HOST\n");
  46. while ((ut = getutent()) != NULL) {
  47. if (ut->ut_user[0] && ut->ut_type == USER_PROCESS) {
  48. time_t thyme = ut->ut_tv.tv_sec;
  49. /* ut->ut_line is device name of tty - "/dev/" */
  50. name = concat_path_file("/dev", ut->ut_line);
  51. printf("%-10s %-8s %-8s %-12.12s %s\n", ut->ut_user, ut->ut_line,
  52. (stat(name, &st)) ? "?" : idle_string(st.st_atime),
  53. ctime(&thyme) + 4, ut->ut_host);
  54. if (ENABLE_FEATURE_CLEAN_UP) free(name);
  55. }
  56. }
  57. if (ENABLE_FEATURE_CLEAN_UP) endutent();
  58. return 0;
  59. }