//% help=control/in-background blockAllowMultiple=1 //% blockId="control_in_background" block="run in background" blockGap=8 void inBackground(Action a) { runInBackground(a); }
//This is the main loop that runs the shell and takes in the commands int main(int argc, char const *argv[]) { char *input; pid_t childpid, pipeChild; int status, execStatus, commandTwo; int runInBG = 0, redirToFile = 0, pipefd[2]; struct sigaction childFinished; childFinished.sa_sigaction = endSignal; input = malloc(sizeof(char)*50); printf("Welcome to MaSh, enter a command.\n"); printf(">"); fgets(input,50,stdin); sigaction(SIGCHLD, &childFinished, NULL); while(strcmp(input,"exit\n") != 0) { runInBG = 0; redirToFile = 0; commandTwo = 0; char **args = calloc(10,sizeof(char*)); //parse user input into argument array status = parseInput(input,args); if (status > 1) runInBG = runInBackground(args,status); if (status > 2) redirToFile = redirectToFromFile(runInBG,args,status, &commandTwo); childpid = fork(); if (childpid >= 0) { //fork success if (childpid == 0) { if (redirToFile == 1) { execStatus = writeOptToFile(runInBG,args,status); } else if (redirToFile == 2) { execStatus = readIptFromFile(runInBG,args,status); } else if (redirToFile == 3) { //create pipe if (pipe(pipefd) == -1) { printf("Pipe failed.\n"); } pipeChild = fork(); if (pipeChild >= 0) { //read from the pipe if (pipeChild == 0) { close(1); dup(pipefd[1]); close(pipefd[0]); execStatus = execvp(*args,args); exit(0); } //write to the pipe else { close(0); dup(pipefd[0]); close(pipefd[1]); execStatus = execvp(args[commandTwo],args+commandTwo); } } else { perror("Fork failed."); exit(-1); } } else { //this is supposed to make the output of commands not appear on screen, it doesnt work though if (runInBG == 1) { setpgid(0,0); } execStatus = execvp(*args,args); } if (execStatus < 0) { printf("Command \"%s\" not found.\n", input); } exit(0); } else { //may not need to do this if (runInBG == 1) { waitpid(-1,&status,WNOHANG | WUNTRACED); runInBG = 0; } else waitpid(childpid,&status,0); } } else { printf("Fork failed.\n"); } printf(">"); fgets(input,50,stdin); free(args); } kill(childpid,SIGKILL); printf("logout\n"); printf("\n"); printf("[Process completed]\n"); exit(0); }