3
0

pwdx.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 (3.7 kb)"
  12. //config: default y
  13. //config: help
  14. //config: Report current working directory of a process
  15. //applet:IF_PWDX(APPLET_NOFORK(pwdx, pwdx, BB_DIR_USR_BIN, BB_SUID_DROP, pwdx))
  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. getopt32(argv, "^" "" "\0" "-1");
  26. argv += optind;
  27. do {
  28. char buf[sizeof("/proc/%u/cwd") + sizeof(int)*3];
  29. unsigned pid;
  30. char *s;
  31. char *arg = *argv;
  32. // Allowed on the command line:
  33. // /proc/NUM
  34. // NUM
  35. if (is_prefixed_with(arg, "/proc/"))
  36. arg += 6;
  37. pid = bb_strtou(arg, NULL, 10);
  38. if (errno)
  39. bb_error_msg_and_die("invalid process id: '%s'", arg);
  40. sprintf(buf, "/proc/%u/cwd", pid);
  41. /* NOFORK: only one alloc is allowed; must free */
  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. }