hexedit: new applet
[oweals/busybox.git] / procps / pwdx.c
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
11 //config:config PWDX
12 //config:       bool "pwdx (3.5 kb)"
13 //config:       default y
14 //config:       help
15 //config:       Report current working directory of a process
16
17 //applet:IF_PWDX(APPLET_NOFORK(pwdx, pwdx, BB_DIR_USR_BIN, BB_SUID_DROP, pwdx))
18
19 //kbuild:lib-$(CONFIG_PWDX) += pwdx.o
20
21 //usage:#define pwdx_trivial_usage
22 //usage:       "PID..."
23 //usage:#define pwdx_full_usage "\n\n"
24 //usage:       "Show current directory for PIDs"
25
26 #include "libbb.h"
27
28 int pwdx_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
29 int pwdx_main(int argc UNUSED_PARAM, char **argv)
30 {
31         getopt32(argv, "^" "" "\0" "-1");
32         argv += optind;
33
34         do {
35                 char buf[sizeof("/proc/%u/cwd") + sizeof(int)*3];
36                 unsigned pid;
37                 char *s;
38                 char *arg = *argv;
39
40                 // Allowed on the command line:
41                 // /proc/NUM
42                 // NUM
43                 if (is_prefixed_with(arg, "/proc/"))
44                         arg += 6;
45
46                 pid = bb_strtou(arg, NULL, 10);
47                 if (errno)
48                         bb_error_msg_and_die("invalid process id: '%s'", arg);
49
50                 sprintf(buf, "/proc/%u/cwd", pid);
51
52                 /* NOFORK: only one alloc is allowed; must free */
53                 s = xmalloc_readlink(buf);
54                 // "pwdx /proc/1" says "/proc/1: DIR", not "1: DIR"
55                 printf("%s: %s\n", *argv, s ? s : strerror(errno == ENOENT ? ESRCH : errno));
56                 free(s);
57         } while (*++argv);
58
59         return EXIT_SUCCESS;
60 }