static void parseArguments(parsed p, char *input) { char **argv; char *arg; char *line; char *s; int i; int segments; segments = countArgs(input); if (segments > 0) { // create an array of char pointers argv = malloc(sizeof(char *) * segments); p->argv = argv; // create malloc'd strings line = strdup(input); s = strdup(input); s = strsep(&line, " "); i = 0; while (s != NULL) { if (strlen(s) > 0) { arg = strdup(s); p->argv[i] = arg; // if last argument is "&" if (i+1 == segments && checkBackground(arg)) { // don't add as an argument // change p->background -> TRUE // printf("adding as background..\n"); p->background = TRUE; free(arg); } else if (checkRedirection(arg)) { // don't add as an argument // change p->relevantStream -> new redirection // printf("adding as redirection..\n"); free(arg); } else { // add arg as an argument // increment arg counter in struct // printf("adding as new argv[%d]: #%s#\n", i, arg); // argv[i] = arg; // these two lines are equivalent. // arg = strsep(&arg, "\n"); // remove \n p->argv[i] = arg; p->argc += 1; i += 1; } } s = strsep(&line, " "); } free(line); free(s); } }
int main(int argc, char * argv[]){ char buffer[500]; char *args[10]; char *path = "/bin/"; char fullPath[20]; char *token; int i; int isBackground; do{ isBackground = 0; printf("> "); fgets(buffer, 500, stdin); //checks if the command is exit if (strcmp(buffer, "exit\n")==0){ printf("logout\n\n[Process completed]\n"); exit(0); } token = strtok(buffer, " \n"); i = 0; // parse the command line input while(token!=NULL){ args[i] = token; token = strtok(NULL, " \n"); i++; } args[i] = NULL; pid_t pid = fork(); int type = 0; int status = 0; if (checkBackground(args,i) == 1){ args[i-1] = NULL; isBackground = 1; } if (pid >= 0){ if (pid == 0){ printf("In Child"); //menu(args,i); }else{ printf("In Parent\n"); if (isBackground==1) type = WNOHANG; waitpid(pid, &status, type); if (type == 0) printf("in forground\n"); } }else { printf("Fork Failed\n"); } }while (1); return 0; }