master xplshn/aruu / cmd / pseudo / pwdx.c
 1/* See LICENSE file for copyright and license details. */
 2
 3#include <errno.h>
 4#include <limits.h>
 5#include <stdio.h>
 6#include <string.h>
 7#include <unistd.h>
 8
 9#include "util.h"
10
11static void
12usage(void)
13{
14  eprintf("usage: %s pid...\n", argv0);
15}
16
17// ?man pwdx: print working directory of process
18// ?man arguments: pid...
19// ?man display the current working directory of a process by pid
20int
21main(int argc, char *argv[])
22{
23  int     ret = 0;
24  char    path[PATH_MAX];
25  char    target[PATH_MAX + sizeof(" (deleted)")];
26  ssize_t n;
27
28  ARGBEGIN
29  {
30    default:
31      usage();
32  }
33  ARGEND;
34
35  if (argc == 0)
36    usage();
37
38  for (; argc > 0; argc--, argv++) {
39    n = snprintf(path, sizeof(path), "/proc/%s/cwd", *argv);
40    if (n < 0 || (size_t)n >= sizeof(path)) {
41      errno = ESRCH;
42    } else {
43      n = readlink(path, target, sizeof(target) - 1);
44      if (n >= 0) {
45        target[n] = '\0';
46        printf("%s: %s\n", *argv, target);
47        continue;
48      }
49    }
50    if (errno == ENOENT)
51      errno = ESRCH;
52    weprintf("%s:", *argv);
53    ret = 1;
54  }
55
56  return ret;
57}