1 |
/* $Id: min_shell.c,v 1.15 2006/06/16 19:48:14 joko Exp $ */ |
2 |
|
3 |
#include <stdlib.h> |
4 |
#include <stdio.h> |
5 |
#include <errno.h> |
6 |
#include <string.h> |
7 |
|
8 |
#include "min_shell.h" |
9 |
|
10 |
int main(int argc, char * argv[]) { |
11 |
|
12 |
// interactive mode with prompt |
13 |
if (argc == 1) { |
14 |
fprintf(stderr, "Welcome to mini shell. Have fun!\n"); |
15 |
run_commands(stdin, "> "); |
16 |
|
17 |
// scripting mode |
18 |
} else if (argc == 2) { |
19 |
FILE * script; |
20 |
script = fopen(argv[1], "r"); |
21 |
if (script == NULL) { |
22 |
perror(NULL); |
23 |
exit(EXIT_FAILURE); |
24 |
} |
25 |
run_commands(script, ""); |
26 |
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) { |
34 |
|
35 |
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)) { |
41 |
|
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 |
54 |
chomp(command_ptr); |
55 |
|
56 |
// trim whitespace |
57 |
trim(&command_ptr); |
58 |
|
59 |
// ... and action |
60 |
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 |
} |
68 |
|
69 |
|
70 |
void dispatch_command(char * command) { |
71 |
|
72 |
BOOL background = FALSE; |
73 |
int command_length; |
74 |
char first_char; |
75 |
char * shell_command; |
76 |
|
77 |
// is it a shell command? |
78 |
first_char = command[0]; |
79 |
if (strcmp(&first_char, ":") == 0) { |
80 |
|
81 |
// "calculate" shell command ... |
82 |
shell_command = command + 1; |
83 |
//printf("shell command: %s\n", shell_command); |
84 |
|
85 |
// ... and dispatch it |
86 |
|
87 |
// wait |
88 |
if (strcmp(shell_command, "wait") == 0) { |
89 |
// TODO |
90 |
os_wait_for_processes(); |
91 |
|
92 |
// exit |
93 |
} else if (strcmp(shell_command, "exit") == 0) { |
94 |
exit(EXIT_SUCCESS); |
95 |
|
96 |
// unknown command |
97 |
} else { |
98 |
fprintf(stderr, "ERROR: Unknown shell command '%s'\n", shell_command); |
99 |
} |
100 |
|
101 |
// run program: background or foreground? |
102 |
} else { |
103 |
//printf("running: %s\n", command); |
104 |
command_length = strlen(command); |
105 |
if (command[command_length-1] == '&' && command[command_length-2] == ' ') { |
106 |
command[command_length-1] = '\0'; |
107 |
command[command_length-2] = '\0'; |
108 |
background = TRUE; |
109 |
} |
110 |
|
111 |
os_start_process(command, background); |
112 |
} |
113 |
} |
114 |
|