-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.c
342 lines (300 loc) · 9.26 KB
/
shell.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#define MAX_LENGTH 1000
#define LOG_FILE "/home/amencsed/Desktop/UbuntuShell/logfile.txt"
#define RESET "\033[0m"
#define BLACK "\033[30m"
#define RED "\033[31m"
#define GREEN "\033[32m"
#define YELLOW "\033[33m"
#define BLUE "\033[34m"
#define MAGENTA "\033[35m"
#define CYAN "\033[36m"
#define WHITE "\033[37m"
// for dealing with the logfile
FILE* file_logger;
/* command type can either be built in command or normal command or exit command */
typedef enum {
built_in_shell_command, normal_command, exit_command_shell
}command_type;
//in file
/* logging the child process the logging file*/
void write_to_log_file(pid_t pid, int status) {
file_logger = fopen(LOG_FILE, "a");
if (file_logger != NULL) {
fprintf(file_logger, "Child process %d %s with status code %d\n", pid,
WIFEXITED(status) ? "exited" : WIFSIGNALED(status) ? "was terminated by signal" : "was stopped by signal",
WEXITSTATUS(status));
fclose(file_logger);
}
}
/*
the function to reap zombie child processes
waitpid() suspends the calling process
until the system gets status information
on the child process and using pooling mode WNOHANG
pid < -1 : means wait for any process with group id = abs(pid)
pid = 0 : means wait for any process with group id = calling id
pid = -1 : means wait for any process
pid > 0 : means wait for that specific process with that id
WNOHANG : means terminate the child process immediately (non blocking mode)
WUNTRACED : means return the status info of child process only if child terminates (blocking mode)
*/
void reap_child_zombie() {
int status;
pid_t pid;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
write_to_log_file(pid, status);
}
}
/* signal handler for parent */
void on_child_exit () {
reap_child_zombie();
}
/* set the home directory as the default directory */
void setup_environment(){
chdir(getenv("HOME"));
}
/* execute cd command*/
void cd(char* command_parameters[]) {
char *path;
if (command_parameters[1] == NULL) {
chdir(getenv("HOME"));
return;
}
if (*command_parameters[1] == '~') {
path = malloc(strlen(getenv("HOME")) + strlen(command_parameters[1] + 1) + 1);
strcpy(path, getenv("HOME"));
strcat(path, command_parameters[1] + 1);
if (chdir(path) != 0) {
perror(RED "cd");
}
}
else {
if (chdir(command_parameters[1]) != 0) {
perror(RED "cd");
}
}
}
/* execute export command */
void export (char command[]) {
char *name, *value;
name = strsep(&command, "="); // = is the delimter
value = strdup(command);
// for qoutes
if (value[0] == '"' && value[strlen(value) - 1] == '"') {
value[strlen(value) - 1] = '\0';
value++;
}
setenv(name, value, 1);
}
/* execute the echo*/
void echo(char command[]) {
// for qoutes
if (command[0] == '"' && command[strlen(command) - 1] == '"') {
command[strlen(command) - 1] = '\0';
command++;
}
printf("%s\n", command);
}
// execute built-in commands: cd, echo, export
void execute_shell_bultin(char *parameters[]) {
char *command = parameters[0];
if (strcmp(command, "cd") == 0) {
cd(parameters);
}
else if (strcmp(command, "echo") == 0) {
echo(parameters[1]);
}
else if (strcmp(command, "export") == 0) {
export(parameters[1]);
}
}
//forking a new child process
void execute_command(char *parameters[], int background) {
pid_t pid = fork();
int status;
if (pid < 0) {
perror(RED "Forking failed");
exit(1);
}
else if (pid == 0) {
if (background) {
printf("process: %d\n", getpid());
//sleep(10);
}
execvp(parameters[0], parameters);
printf(RED "%s: command not found\n", parameters[0]);
exit(1);
}
else {
if (background) {
// return immediately
waitpid(pid, &status, WNOHANG);
}
else {
// wait till child ends
waitpid(pid, &status, 0);
}
}
}
char* remove_starting_trailing_spaces(char *command) {
/* remove spaces at the start */
while (command[0] == ' ') {
command++;
}
/* remove spaces at the end */
while (command[strlen(command) - 1] == ' ') {
command[strlen(command) - 1] = '\0';
}
return command;
}
/* read the command and terminate at "\n" excape character*/
void read_command (char command[]) {
char cwd[MAX_LENGTH];
getcwd(cwd, sizeof(cwd));
printf(MAGENTA "%s", cwd);
printf(YELLOW "$");
printf(BLUE " ");
fgets(command, MAX_LENGTH, stdin);
command[strcspn(command, "\n")] = '\0';
}
/* replace var by its value */
char* replace_var(char* input_command, int foundAt) {
char var[MAX_LENGTH];
int v = 0;
char output_command[MAX_LENGTH];
int k = 0;
// characters before $
for (int i = 0; i < foundAt; i++) {
output_command[k++] = input_command[i];
}
for (int i = foundAt + 1; i < strlen(input_command); i++) {
if (input_command[i] != '$' && input_command[i] != ' ' && input_command[i] != '"') {
var[v++] = input_command[i];
}
else {
var[v++] = '\0';
break;
}
}
char *value = getenv(var);
// plug in var's value
if (value != NULL) {
for (int i = 0; i < strlen(value); i++) {
output_command[k++] = value[i];
}
}
// then complete the string with the remaining characters
for (int i = foundAt + strlen(var) + 1; i < strlen(input_command); i++) {
output_command[k++] = input_command[i];
}
output_command[k++] = '\0';
strcpy(input_command, output_command); // updates the input by the var value
return input_command;
}
/* parse the command and get the parameters of it*/
void parse_command(char command[], char* parameters[]) {
// consecutively remove $var by value
while (1) {
int i = 0;
int flag = 0;
while (i < strlen(command)) {
if (command[i] == '$') {
flag = 1;
break;
}
i++;
}
if (!flag) {
break;
}
command = replace_var(command, i);
}
char *delimiter = " ";
int arg_count = 0;
char *token = strtok(command, delimiter);
char *first_token = strdup(token);
// Check if the first token is a built-in command
if (strcmp(first_token, "cd") == 0
|| strcmp(first_token, "echo") == 0
|| strcmp(first_token, "export") == 0) {
while (token != NULL && arg_count < MAX_LENGTH) {
parameters[arg_count++] = strdup(token);
token = strtok(NULL, "");
}
}
else {
while (token != NULL && arg_count < MAX_LENGTH) {
parameters[arg_count++] = token;
token = strtok(NULL, " ");
}
}
}
/* begin to execute the commands */
void shell () {
int command_exit = 0;
do {
char command [MAX_LENGTH] = {};
char *parameters [MAX_LENGTH] = {};
command_type cmd_type;
int background = 0;
/* read the input and removed the un-necessary spaces*/
read_command(command);
strcpy(command, remove_starting_trailing_spaces(command));
if(strlen(command) == 0){
continue;
}
/* detected that it is background */
if (command[strlen(command) - 1] == '&') {
background = 1;
command[strlen(command) - 1] = '\0';
remove_starting_trailing_spaces(command);
}
parse_command(command, parameters);
/* detected it is exit command */
if (strcmp(parameters[0], "exit") == 0) {
command_exit = 1;
cmd_type = exit_command_shell;
}
/* detected it is built in shell command */
else if (strcmp(parameters[0], "cd") == 0
|| strcmp(parameters[0], "echo") == 0
|| strcmp(parameters[0], "export") == 0) {
cmd_type = built_in_shell_command;
}
/* normal command detected */
else {
cmd_type = normal_command;
}
switch (cmd_type) {
case built_in_shell_command:
execute_shell_bultin(parameters);
break;
case normal_command:
execute_command(parameters, background);
break;
case exit_command_shell:
break;
}
} while (!command_exit); // while not exit command
}
int main() {
printf(GREEN " ========================================================\n");
printf(GREEN " ================ WELCOME TO MY SHELL !! ================\n");
printf(GREEN " ========================================================\n");
/*
this signal informs the parent process
to clean up the child process
*/
signal(SIGCHLD, on_child_exit);
//to home directory
setup_environment();
// begin reading & executing commands in terminal
shell();
return 0;
}