]> Trent Huber's Code - thus.git/commitdiff
Execute commands
authorTrent Huber <trentmhuber@gmail.com>
Mon, 5 May 2025 07:35:49 +0000 (03:35 -0400)
committerTrent Huber <trentmhuber@gmail.com>
Mon, 5 May 2025 07:35:49 +0000 (03:35 -0400)
.gitignore [new file with mode: 0644]
.gitmodules [new file with mode: 0644]
build.c [new file with mode: 0644]
external/cbs [new submodule]
main.c [new file with mode: 0644]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..3ac8fc1
--- /dev/null
@@ -0,0 +1,3 @@
+*.o
+ash
+build
diff --git a/.gitmodules b/.gitmodules
new file mode 100644 (file)
index 0000000..4ab3ff4
--- /dev/null
@@ -0,0 +1,3 @@
+[submodule "external/cbs"]
+   path = external/cbs
+   url = https://github.com/trenthuber/cbs
diff --git a/build.c b/build.c
new file mode 100644 (file)
index 0000000..2ab0877
--- /dev/null
+++ b/build.c
@@ -0,0 +1,10 @@
+#include "external/cbs/cbs.c"
+
+int main(void) {
+   build(NULL);
+
+   compile("main", NULL);
+   load('x', "ash", "main", NULL);
+
+   return EXIT_SUCCESS;
+}
diff --git a/external/cbs b/external/cbs
new file mode 160000 (submodule)
index 0000000..47c262d
--- /dev/null
@@ -0,0 +1 @@
+Subproject commit 47c262dc02e5f6ed3dba9e092a5f750084bfad95
diff --git a/main.c b/main.c
new file mode 100644 (file)
index 0000000..eab4047
--- /dev/null
+++ b/main.c
@@ -0,0 +1,59 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/errno.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#define BUFLEN 1024
+
+char **tokenize(char *p) {
+   size_t i;
+   static char *result[BUFLEN / 2];
+
+   for (i = 0; *p != '\n'; ++i) {
+       result[i] = p;
+       while (*p != ' ' && *p != '\n') ++p;
+       *p++ = '\0';
+       if (*p == '\0') break;
+       while (*p == ' ') ++p;
+   }
+   result[i + 1] = NULL;
+   return result;
+}
+
+int main(void) {
+   char buffer[BUFLEN];
+   char **tokens;
+   pid_t cpid;
+   int status;
+
+   for (;;) {
+       printf("%% ");
+       if (fgets(buffer, BUFLEN, stdin) == NULL) {
+           if (feof(stdin)) {
+               printf("\n");
+               exit(EXIT_SUCCESS);
+           }
+           dprintf(STDERR_FILENO, "ash: Couldn't read input");
+           if (!ferror(stdin)) dprintf(STDERR_FILENO, ": %s", strerror(errno));
+           dprintf(STDERR_FILENO, "\n");
+           exit(EXIT_FAILURE);
+       }
+       tokens = tokenize(buffer);
+
+       if ((cpid = fork()) == 0)
+           if (execvp(tokens[0], tokens) == -1) {
+               dprintf(STDERR_FILENO, "ash: Unable to run command `%s': %s\n",
+                       tokens[0], strerror(errno));
+               exit(EXIT_FAILURE);
+           }
+       if (waitpid(cpid, &status, 0) == -1) {
+           dprintf(STDERR_FILENO, "ash: Unable to await command `%s': %s\n",
+                   tokens[0], strerror(errno));
+           exit(EXIT_FAILURE);
+       }
+       // TODO: Handle WIFEXITED, WIFSIGNALED, WIFSTOPPED differently
+   }
+   return 0;
+}