From f29eb775b92555d14a2d8a91126c339766052ba9 Mon Sep 17 00:00:00 2001 From: Trent Huber Date: Mon, 5 May 2025 03:35:49 -0400 Subject: [PATCH] Execute commands --- .gitignore | 3 +++ .gitmodules | 3 +++ build.c | 10 +++++++++ external/cbs | 1 + main.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 76 insertions(+) create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 build.c create mode 160000 external/cbs create mode 100644 main.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3ac8fc1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.o +ash +build diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..4ab3ff4 --- /dev/null +++ b/.gitmodules @@ -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 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 index 0000000..47c262d --- /dev/null +++ b/external/cbs @@ -0,0 +1 @@ +Subproject commit 47c262dc02e5f6ed3dba9e092a5f750084bfad95 diff --git a/main.c b/main.c new file mode 100644 index 0000000..eab4047 --- /dev/null +++ b/main.c @@ -0,0 +1,59 @@ +#include +#include +#include +#include +#include +#include + +#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; +} -- 2.51.0