diff --git a/apps/src/sh.c b/apps/src/sh.c index 0b229810..9e605f31 100644 --- a/apps/src/sh.c +++ b/apps/src/sh.c @@ -1,6 +1,7 @@ #include #include #include +#include #include #include @@ -9,8 +10,8 @@ static int status; typedef struct { char* buffer; - long size; - long capacity; + size_t size; + size_t capacity; } command; void show_prompt() @@ -18,6 +19,33 @@ void show_prompt() printf("[%ld]> ", getpid()); } +int command_matches(command* cmd, const char* string) +{ + if (cmd->size <= strlen(string)) // cmd->size includes null terminator + return 0; + return strncmp(cmd->buffer, string, strlen(string)) == 0; +} + +int command_matches_exactly(command* cmd, const char* string) +{ + if (cmd->size <= strlen(string)) // cmd->size includes null terminator + return 0; + if (cmd->size > (strlen(string) + 1)) return 0; + return strncmp(cmd->buffer, string, strlen(string)) == 0; +} + +int command_match_builtins(command* cmd) +{ + if (command_matches(cmd, "exit ")) { exit(atoi(cmd->buffer + 5)); } + if (command_matches_exactly(cmd, "exit")) { exit(0); } + if (command_matches_exactly(cmd, "pid")) + { + printf("pid %ld, ppid %ld\n", getpid(), getppid()); + return 1; + } + return 0; +} + void command_expand(command* cmd, long new_capacity) { char* buffer = realloc(cmd->buffer, new_capacity); @@ -58,6 +86,12 @@ void command_clear(command* cmd) void command_execute(command* cmd) { command_push(cmd, '\0'); + if (command_match_builtins(cmd)) + { + command_clear(cmd); + show_prompt(); + return; + } pid_t child = fork(); if (child < 0) {