who.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 <stdio.h>
  17. #include <stdlib.h>
  18. #include <utmp.h>
  19. #include <sys/stat.h>
  20. #include <time.h>
  21. #include "busybox.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 (const char *) 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. /* ut->ut_line is device name of tty - "/dev/" */
  49. name = concat_path_file("/dev", ut->ut_line);
  50. printf("%-10s %-8s %-8s %-12.12s %s\n", ut->ut_user, ut->ut_line,
  51. (stat(name, &st)) ? "?" : idle_string(st.st_atime),
  52. ctime((time_t*)&(ut->ut_tv.tv_sec)) + 4, ut->ut_host);
  53. free(name);
  54. }
  55. }
  56. endutent();
  57. return 0;
  58. }