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