summaryrefslogtreecommitdiff
path: root/src/cmd/ps/ps.c
blob: a4b2e4cd724fba9a48ef67a6a7b8c045c3867082 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <_proc.h>
#include <ctype.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void
usage(void)
{
	fprintf(stderr, "usage: ps [path]\n");
	exit(1);
}

int
main(int argc, const char *argv[])
{
	const char *path = argc >= 2 ? argv[1] : "/proc/";
	if (argc > 2) usage();

	char *readbuf = malloc(4096);
	char *procbuf = malloc(4096);
	FILE *f = fopen(path, "r");
	if (!f) {
		err(1, "couldn't open %s", path);
	}

	// TODO library for iterating over directories
	for (;;) {
		int len = fread(readbuf, 1, 4096, f);
		if (len <= 0) break;
		for (int pos = 0; pos < len; ) {
			char *end = memchr(readbuf + pos, 0, len - pos);
			if (!end) {
				errx(1, "unimplemented: buffer overflow");
			}
			size_t entryl = end - (readbuf+pos) + 1;
			if (isdigit(readbuf[pos])) {
				FILE *g;
				sprintf(procbuf, "%s%smem", path, readbuf+pos);
				g = fopen(procbuf, "r");
				if (!g) {
					warn("couldn't open \"%s\"", procbuf);
					strcpy(procbuf, "(can't peek)");
				} else {
					fseek(g, (long)&_psdata_loc->desc, SEEK_SET);
					if (fread(procbuf, 1, 128, g) <= 0) {
						strcpy(procbuf, "(no psdata)");
					}
					procbuf[128] = '\0';
					fclose(g);
				}
				end[-1] = '\0'; /* remove trailing slash */
				printf("%s\t%s\n", readbuf+pos, procbuf);
			}
			pos += entryl;
		}
	}

	free(readbuf);
	free(procbuf);
	fclose(f);
	return 0;
}