From a9d4503bfe1180859d775748b10f21983f611e9e Mon Sep 17 00:00:00 2001 From: aaron Date: Tue, 12 May 2026 15:56:51 +0200 Subject: [PATCH] added background job support. --- main.c | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/main.c b/main.c index 94a83c5..4454d80 100644 --- a/main.c +++ b/main.c @@ -6,17 +6,28 @@ #include #include #include +pid_t backgroundPids[64]; +int backgroundCount = 0; void handleSIGINT(int sig) { printf("\n"); } -int detectBackgrount(char **args) { +void handleSIGCHLD(int sig) { + int pid = waitpid(-1, NULL, WNOHANG); + for(int i = 0; i < backgroundCount; i++) { + if(backgroundPids[i] == pid) { + printf("\n[done] %d\n", pid); + backgroundPids[i] = 0; // clear it + } + } +} +int detectBackground(char **args) { for (int i = 0; args[i] != NULL; i++) { if (strcmp(args[i], "&") == 0) { args[i] = NULL; - return 0; + return 1; } } - return 1; + return 0; } int seperatePipe(char **args) { for(int i = 0; args[i] != NULL; i++) { @@ -78,6 +89,7 @@ char **parse(char *line) { } int main() { signal(SIGINT, handleSIGINT); + signal(SIGCHLD, handleSIGCHLD); while(1) { char *user = getenv("USER"); char dir[1024]; @@ -92,7 +104,7 @@ int main() { char **parsed = parse(line); if(parsed[0] == NULL) { free(parsed); free(line); continue; } if(handleBuiltins(parsed)) { free(line); free(parsed); continue; } - int background = detectBackgrount(parsed); + int background = detectBackground(parsed); int pipeIndex = seperatePipe(parsed); if (pipeIndex != -1) { executePipe(parsed, pipeIndex); @@ -102,13 +114,18 @@ int main() { } pid_t pid = fork(); if(pid == 0) { + signal(SIGINT, SIG_DFL); if(execvp(parsed[0], parsed) == -1 ) { perror("tinysh"); exit(1); } - } else if(pid > 0 && background != 0) { - wait(NULL); - } + } else if(pid > 0) { + if(background) { + printf("{background} %d \n", pid); + backgroundPids[backgroundCount++] = pid; + } + else wait(NULL); + } free(parsed); free(line); }