From 2ad6ee8ed15d1bf898645a16dbc06991a3c1425e Mon Sep 17 00:00:00 2001
From: dzwdz
Date: Wed, 25 Jan 2023 19:22:18 +0100
Subject: user: process titles, /bin/ps

---
 src/user/app/init/init.c |  4 +--
 src/user/app/ps/ps.c     | 73 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 74 insertions(+), 3 deletions(-)
 create mode 100644 src/user/app/ps/ps.c

(limited to 'src/user/app')

diff --git a/src/user/app/init/init.c b/src/user/app/init/init.c
index 73e863e..d872b24 100644
--- a/src/user/app/init/init.c
+++ b/src/user/app/init/init.c
@@ -41,7 +41,7 @@ int main(void) {
 
 	freopen("/kdev/com1", "a+", stdout);
 	freopen("/kdev/com1", "a+", stderr);
-	printf("[init] stage 2, main at %p, testtr at %p\n", &main, teststr);
+	printf("[init] stage 2, main at %p, teststr at %p\n", &main, teststr);
 
 	MOUNT_AT("/keyboard") {
 		MOUNT_AT("/") { fs_whitelist((const char*[]){"/kdev/ps2/kb", NULL}); }
@@ -101,8 +101,6 @@ int main(void) {
 		close(killswitch_pipe[0]);
 		redirect("/bin/shell", "/kdev/com1", "/kdev/com1");
 		redirect("/bin/shell", "/vtty", "/keyboard");
-		// TODO busy loop without no children
-		for (;;) _syscall_await();
 		exit(1);
 	}
 
diff --git a/src/user/app/ps/ps.c b/src/user/app/ps/ps.c
new file mode 100644
index 0000000..78d4204
--- /dev/null
+++ b/src/user/app/ps/ps.c
@@ -0,0 +1,73 @@
+#include <_proc.h>
+#include <ctype.h>
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* returns a pointer that can be set to NUL to undo the strcat */
+static char *
+strtcat(char *dst, const char *src)
+{
+	char *s = dst + strlen(dst);
+	strcpy(s, src);
+	return s;
+}
+
+static void
+do_proc(char *path)
+{
+	const int bufl = 4096;
+	char *buf = malloc(bufl);
+	FILE *f;
+
+	{ /* read the psdata into buf */
+		char *s = strtcat(path, "mem");
+		f = fopen(path, "r");
+		*s = '\0';
+		if (!f) errx(1, "couldn't open '%s'", path);
+		fseek(f, (long)_libc_psdata, SEEK_SET);
+		if (fread(buf, 1, 128, f) <= 0) {
+			strcpy(buf, "(no psdata)");
+		}
+		buf[128] = '\0';
+		fclose(f);
+	}
+
+	printf("%20s %s\n", path, buf);
+
+	f = fopen(path, "r");
+	if (!f) errx(1, "couldn't open '%s'", path);
+
+	// TODO library for iterating over directories
+	for (;;) {
+		int len = fread(buf, 1, bufl, f);
+		if (len <= 0) break;
+		for (int pos = 0; pos < len; ) {
+			const char *end = memchr(buf + pos, 0, len - pos);
+			if (!end) {
+				errx(1, "unimplemented: buffer overflow");
+			}
+			size_t entryl = end - (buf + pos) + 1;
+			if (isdigit(buf[pos])) {
+				/* yup, no overflow check */
+				char *s = strtcat(path, buf + pos);
+				do_proc(path);
+				*s = '\0';
+			}
+			pos += entryl;
+		}
+	}
+
+	free(buf);
+	fclose(f);
+}
+
+int
+main(void)
+{
+	char *buf = malloc(4096);
+	strcpy(buf, "/proc/");
+	do_proc(buf);
+	return 0;
+}
-- 
cgit v1.2.3