added background job support.
This commit is contained in:
@@ -6,17 +6,28 @@
|
||||
#include<readline/readline.h>
|
||||
#include<readline/history.h>
|
||||
#include<signal.h>
|
||||
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 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,12 +114,17 @@ 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);
|
||||
|
||||
Reference in New Issue
Block a user