| 11 |
|
|
| 12 |
// interactive mode with prompt |
// interactive mode with prompt |
| 13 |
if (argc == 1) { |
if (argc == 1) { |
| 14 |
fprintf(stderr, "Interactive mode not implemented yet.\n"); |
fprintf(stderr, "Welcome to mini shell. Have fun!\n"); |
| 15 |
//printf("No arguments given."); |
run_commands(stdin, "> "); |
|
exit(EXIT_FAILURE); |
|
|
} |
|
| 16 |
|
|
| 17 |
// scripting mode |
// scripting mode |
| 18 |
if (argc == 2) { |
} else if (argc == 2) { |
| 19 |
FILE * script = fopen(argv[1], "r"); |
FILE * script; |
| 20 |
run_commands(script); |
script = fopen(argv[1], "r"); |
| 21 |
|
if (script == NULL) { |
| 22 |
|
perror(NULL); |
| 23 |
|
exit(EXIT_FAILURE); |
| 24 |
|
} |
| 25 |
|
run_commands(script, ""); |
| 26 |
fclose(script); |
fclose(script); |
| 27 |
|
|
| 28 |
|
} else { |
| 29 |
|
fprintf(stderr, "Sorry, mini shell just accepts one parameter: a path to a script!\n"); |
| 30 |
} |
} |
| 31 |
} |
} |
| 32 |
|
|
| 33 |
void run_commands(FILE * fp) { |
void run_commands(FILE * fp, char * prompt) { |
| 34 |
|
|
| 35 |
char command[MAX_COMMAND_LENGTH]; |
char command[MAX_COMMAND_LENGTH]; |
| 36 |
|
char *command_ptr; |
| 37 |
|
|
| 38 |
|
// echo first prompt |
| 39 |
|
fprintf(stdout, "%s", prompt); |
| 40 |
while (fgets(command, MAX_COMMAND_LENGTH, fp)) { |
while (fgets(command, MAX_COMMAND_LENGTH, fp)) { |
| 41 |
int command_length; |
|
| 42 |
|
int error_number = ferror(fp); |
| 43 |
|
|
| 44 |
|
if (error_number) { |
| 45 |
|
char * message = strerror(error_number); |
| 46 |
|
fprintf(stderr, "Error while reading from input stream: %s", message); |
| 47 |
|
clearerr(fp); |
| 48 |
|
break; |
| 49 |
|
} |
| 50 |
|
|
| 51 |
|
command_ptr = command; |
| 52 |
|
|
| 53 |
// strip newlines |
// strip newlines |
| 54 |
chomp(command); |
chomp(command_ptr); |
| 55 |
|
|
| 56 |
|
// trim whitespace |
| 57 |
|
trim(&command_ptr); |
| 58 |
|
|
| 59 |
// ... and action |
// ... and action |
| 60 |
dispatch_command(command); |
if (strlen(command_ptr)) |
| 61 |
|
dispatch_command(command_ptr); |
| 62 |
|
|
| 63 |
|
// echo prompt after executing shell command |
| 64 |
|
fprintf(stdout, "%s", prompt); |
| 65 |
} |
} |
| 66 |
|
|
| 67 |
} |
} |
| 102 |
} else { |
} else { |
| 103 |
//printf("running: %s\n", command); |
//printf("running: %s\n", command); |
| 104 |
command_length = strlen(command); |
command_length = strlen(command); |
| 105 |
if (command[command_length-1] == '&') { |
if (command[command_length-1] == '&' && command[command_length-2] == ' ') { |
| 106 |
command[command_length-1] = '\0'; |
command[command_length-1] = '\0'; |
| 107 |
|
command[command_length-2] = '\0'; |
| 108 |
background = TRUE; |
background = TRUE; |
| 109 |
} |
} |
| 110 |
|
|