| 13 |
if (argc == 1) { |
if (argc == 1) { |
| 14 |
fprintf(stderr, "Welcome to mini shell. Have fun!\n"); |
fprintf(stderr, "Welcome to mini shell. Have fun!\n"); |
| 15 |
run_commands(stdin, "> "); |
run_commands(stdin, "> "); |
|
} |
|
| 16 |
|
|
| 17 |
// scripting mode |
// scripting mode |
| 18 |
if (argc == 2) { |
} else if (argc == 2) { |
| 19 |
FILE * script = fopen(argv[1], "r"); |
FILE * script; |
| 20 |
|
script = fopen(argv[1], "r"); |
| 21 |
|
if (script == NULL) { |
| 22 |
|
perror(NULL); |
| 23 |
|
exit(EXIT_FAILURE); |
| 24 |
|
} |
| 25 |
run_commands(script, ""); |
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, char * prompt) { |
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 |
// echo first prompt |
| 39 |
fprintf(stdout, "%s", prompt); |
fprintf(stdout, "%s", prompt); |
| 40 |
while (fgets(command, MAX_COMMAND_LENGTH, fp)) { |
while (fgets(command, MAX_COMMAND_LENGTH, fp)) { |
| 41 |
char *command_ptr = command; |
|
| 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_ptr); |
chomp(command_ptr); |