pwdx.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * pwdx implementation for busybox
  4. *
  5. * Copyright (c) 2004 Nicholas Miell
  6. * ported from procps by Pere Orga <gotrunks@gmail.com> 2011
  7. *
  8. * Licensed under GPLv2, see file LICENSE in this source tree.
  9. */
  10. //config:config PWDX
  11. //config: bool "pwdx"
  12. //config: default y
  13. //config: help
  14. //config: Report current working directory of a process
  15. //applet:IF_PWDX(APPLET(pwdx, BB_DIR_USR_BIN, BB_SUID_DROP))
  16. //kbuild:lib-$(CONFIG_PWDX) += pwdx.o
  17. //usage:#define pwdx_trivial_usage
  18. //usage: "PID..."
  19. //usage:#define pwdx_full_usage "\n\n"
  20. //usage: "Show current directory for PIDs"
  21. #include "libbb.h"
  22. int pwdx_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  23. int pwdx_main(int argc UNUSED_PARAM, char **argv)
  24. {
  25. opt_complementary = "-1";
  26. getopt32(argv, "");
  27. argv += optind;
  28. do {
  29. char buf[sizeof("/proc/%u/cwd") + sizeof(int)*3];
  30. unsigned pid;
  31. char *s;
  32. char *arg = *argv;
  33. // Allowed on the command line:
  34. // /proc/NUM
  35. // NUM
  36. if (is_prefixed_with(arg, "/proc/"))
  37. arg += 6;
  38. pid = bb_strtou(arg, NULL, 10);
  39. if (errno)
  40. bb_error_msg_and_die("invalid process id: '%s'", arg);
  41. sprintf(buf, "/proc/%u/cwd", pid);
  42. s = xmalloc_readlink(buf);
  43. // "pwdx /proc/1" says "/proc/1: DIR", not "1: DIR"
  44. printf("%s: %s\n", *argv, s ? s : strerror(errno == ENOENT ? ESRCH : errno));
  45. free(s);
  46. } while (*++argv);
  47. return EXIT_SUCCESS;
  48. }