what doing: creating custom shell class project. started implementing fork , exec features.
my issue: ls
works fine until change directories cd
. after first cd
, ls
requires .
list files in current directory. after that, seems lose functionality.
i've included code below. (including pointing out obvious newb mistakes) appreciated. in stages of grasping these concepts.
int main(){ char *input = malloc(sizeof(char*) * buffersize); char *token; char **token_array; int i; int return_status; printf("%s", boilerplate); if (input == null){ printf("jash: buffer allocation failed"); return 1; } // shell loop while(1){ = 0; printf("jash:> "); fgets(input, buffersize, stdin); token_array = malloc(sizeof(char)*strlen(input)); token = strtok(input, " \n()<>|&;"); while(token != null){ token_array[i] = token; token = strtok(null, " \n()<>|&;"); i++; } // print tokens confirm correct parsing of input printf("%s : %s\n", token_array[0], token_array[1]); //printf("%s\n", token_array[0]); if(exec_args(token_array) == 0){ // programm exit free(token_array); free(input); return 0;; } free(token_array); } // loop end // free input buffer before exit //free(token_array); free(input); return 0; } int exec_args(char ** t){ int i; if(strcmp(t[0], "exit") == 0 || strcmp(t[0], "quit") == 0 || strcmp(t[0], "logout") == 0){ // call built in function exit exit(0); } if (strcmp(t[0], "cd") == 0){ // call built in function chdir if(chdir(t[1]) == 0){ printf("successfully changed directories %s\n", t[1]); return 1; } else { printf("-jash: cd: %s: no such file or directory\n", t[1]); return 1; } } if (strcmp(t[0], "pwd") == 0) { char * p = malloc(sizeof(char*) * 100); getcwd(p, 100); printf("%s\n", p); free(p); return 1; } if(strcmp(t[0], "help") == 0){ printf("\n%s\n documentation coming soon!\n\n", boilerplate); return 1; } if(fork() == 0){ if(execvp(t[0], t)){ perror("jash"); } } else { int status; wait(&status); printf("%d", status); } return 1; }
Comments
Post a Comment