diff options
author | dzwdz | 2023-08-31 01:17:58 +0200 |
---|---|---|
committer | dzwdz | 2023-08-31 01:17:58 +0200 |
commit | fd7be968dd3bce84e31d62e1faecef9cf5ea14c1 (patch) | |
tree | a7194a31533038440b5dccd6bf1e25bb51ccde99 /src | |
parent | 6cbe58797781cb8514a62bb3ab0e3e8a5d58bce2 (diff) |
cmd/ps: use dirent.h
Diffstat (limited to 'src')
-rw-r--r-- | src/cmd/ps/ps.c | 54 |
1 files changed, 22 insertions, 32 deletions
diff --git a/src/cmd/ps/ps.c b/src/cmd/ps/ps.c index a4b2e4c..c855251 100644 --- a/src/cmd/ps/ps.c +++ b/src/cmd/ps/ps.c @@ -1,5 +1,6 @@ #include <_proc.h> #include <ctype.h> +#include <dirent.h> #include <err.h> #include <stdio.h> #include <stdlib.h> @@ -18,47 +19,36 @@ 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) { + DIR *dir = opendir(path); + if (!dir) { 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); + struct dirent *de; + while ((de = readdir(dir))) { + const char *name = de->d_name; + if (isdigit(name[0])) { + FILE *g; + sprintf(procbuf, "%s%smem", path, name); + 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)"); } - end[-1] = '\0'; /* remove trailing slash */ - printf("%s\t%s\n", readbuf+pos, procbuf); + procbuf[128] = '\0'; + fclose(g); } - pos += entryl; + *strchr(name, '/') = '\0'; + printf("%s\t%s\n", name, procbuf); } } - free(readbuf); free(procbuf); - fclose(f); + closedir(dir); return 0; } |