commit 43b26afb7baa97d8f78022197118695143a21132
parent ce14fd6525d157cccb7e5a0578c9391ea3007cc6
Author: evenfri <evenfri256@gmail.com>
Date: Mon, 10 Aug 2026 03:24:29 +0800
fix sh
Diffstat:
| M | sh.c | | | 53 | ++++++++++++++++++++++++++++++++++++----------------- |
1 file changed, 36 insertions(+), 17 deletions(-)
diff --git a/sh.c b/sh.c
@@ -8,33 +8,38 @@
static char prompt[] = "; ";
-void execcd(const char *path) {
- chdir(path);
+void exec_cd(const char *path) {
+ if (path != NULL) {
+ chdir(path);
+ }
}
int main(void) {
+ if (environ == NULL) {
+ write(stderr, "environ is NULL\n", 16);
+ } else {
+ write(stderr, "environ OK\n", 11);
+ }
+
char line[max_line];
char *argv[max_args];
while (1) {
+ memset(line, 0, sizeof(line));
+ memset(argv, 0, sizeof(argv));
+
write(stdout, prompt, 2);
ssize_t n = read(stdin, line, max_line - 1);
- if (n <= 0) continue;
+ if (n <= 0) break;
line[n] = '\0';
- if (line[n - 1] == '\n') line[n - 1] = '\0';
-
- if (strlen(line) == 0) continue;
- if (strcmp(line, "clear") == 0) {
- write(stdout, msg_clear, strlen(msg_clear));
- continue;
+ while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) {
+ line[--n] = '\0';
}
- if (strcmp(line, "exit") == 0) {
- break;
- }
+ if (n == 0 || strlen(line) == 0) continue;
int argc = 0;
char *token = strtok(line, " ");
@@ -44,14 +49,28 @@ int main(void) {
}
argv[argc] = NULL;
- if (argc == 0) continue;
+ if (argc == 0 || argv[0] == NULL) continue;
- if (strcmp(line, "cd") == 0) {
- execcd(argv[1]);
+ if (strcmp(argv[0], "clear") == 0) {
+ write(stdout, msg_clear, strlen(msg_clear));
+ continue;
+ }
+
+ if (strcmp(argv[0], "exit") == 0) {
+ break;
+ }
+
+ if (strcmp(argv[0], "cd") == 0) {
+ exec_cd(argv[1]);
continue;
}
int pid = fork();
+ if (pid < 0) {
+ write(stderr, "sh: fork failed\n", 16);
+ continue;
+ }
+
if (pid == 0) {
/* child */
execvp(argv[0], argv);
@@ -60,9 +79,9 @@ int main(void) {
write(stderr, argv[0], strlen(argv[0]));
write(stderr, "\n", 1);
exit(127);
- } else if (pid > 0) {
+ } else {
/* parent */
- int status;
+ int status = 0;
waitpid(pid, &status, 0);
}
}