-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
292 lines (278 loc) · 7.31 KB
/
main.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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <stdbool.h>
#include <signal.h>
//for text colors
#define MAGENTA "\x1b[35m"
#define YEL "\e[0;33m"
#define reset "\x1b[0m"
#define MAX_COMMAND_LENGTH 1000
#define MAX_ARGUMENTS 100
char command[MAX_COMMAND_LENGTH];
char *arr[MAX_ARGUMENTS];
char *token;
char *value;
int i;
int k;
FILE *file;
int flag = 0;
pid_t id;
// functions prototypes
void setup_environment();
void parse_input();
void shell();
void execute_shell_builtin(char[]);
void execute_command();
void on_child_exit(pid_t);
void on_signal_exit();
void write_to_log_file(pid_t);
void remove_quotes(char *);
int main()
{
// Register a signal handler for child process termination
signal(SIGCHLD, on_signal_exit);
// Initialize the shell environment and start the main loop
setup_environment();
shell();
return 0;
}
// Sets up the shell environment by prompting the user for input and parsing it
void setup_environment()
{
// Prompt the user for input
char directory[1000];
// get the name of the working directory
getcwd(directory, sizeof(directory));
chdir(directory);
//display the prompt
printf(MAGENTA "SIMPLE-SHELL:" reset YEL "%s >>" reset, directory); // print working directory
// Read the user's input
if (!fgets(command, MAX_COMMAND_LENGTH, stdin))
{
perror("Failed to read input");
shell();
}
// repeat function if ENTER button is pressed
if (command[0] == '\n')
shell();
// Remove the newline character
command[strcspn(command, "\n")] = '\0';
parse_input();
}
void parse_input()
{
// Parse the input into tokens
char temp[1000];
strcpy(temp, command);
char *input = strtok(temp, " ");
// Handle export command
if (strcmp(input, "export") == 0)
{
token = command;
arr[0] = strsep(&token, " ");
arr[1] = token;
remove_quotes(arr[1]);
}
else
{
// if the command is anything but export command, tokenize the command into arguments
token = strtok(command, " ");
i = 0;
while (token != NULL)
{
arr[i++] = token;
token = strtok(NULL, " ");
}
arr[i] = NULL;
// handle background execution
if (arr[1] != NULL && !strcmp(arr[1], "&"))
flag = 1;
// Substitute environment variables starting with '$'
for (int j = 0; arr[j] != NULL; j++)
{
if (arr[j][0] == '$')
{
// Extract variable name from the argument
char temp[50];
int l = 0;
for (k = 1; arr[1][k] != '\0'; k++)
{
temp[l++] = arr[1][k];
}
temp[l] = '\0';
// Get the value of the environment variable and replace it in the arguments
char *g = getenv(temp);
strcpy(temp, g);
l = 1;
token = strtok(temp, " ");
while (token != NULL)
{
arr[l++] = token;
token = strtok(NULL, " ");
}
arr[l] = NULL;
}
}
}
// Execute built-in commands (cd, echo, export)
if (strcmp(arr[0], "echo") == 0 || strcmp(arr[0], "cd") == 0 || strcmp(arr[0], "export") == 0)
execute_shell_builtin(arr[0]);
// exit command
else if (strcmp(arr[0], "exit") == 0)
{
kill(id, SIGKILL); // kill zombie before exit
file = fopen("/home/ranime/Desktop/Term6/OS/Labs/Lab1/logs.txt", "a");
fprintf(file, "\n***** SESSION TERMINATED *****\n");
fclose(file);
on_signal_exit();
exit(EXIT_SUCCESS);
}
else
execute_command();
}
// Main shell loop
void shell()
{
do
{
flag = 0;
setup_environment();
} while (true);
}
// Execute built-in commands (cd, echo, export)
void execute_shell_builtin(char string[])
{
switch (string[1])
{
case 'd': // case cd
if (strcmp(string, "cd") == 0)
{
// (~) or No argument provided, go to home directory
if (arr[1] == NULL || strcmp(arr[1], "~") == 0)
{
chdir(getenv("HOME"));
}
else if (strcmp(arr[1], "..") == 0)
{ // Move back one directory
chdir("..");
}
else if (arr[1][0] == '/')
{ // Absolute path
chdir(arr[1]);
}
else
{ // Relative path
char current_path[1024];
getcwd(current_path, sizeof(current_path));
strcat(current_path, "/");
strcat(current_path, arr[1]);
chdir(current_path);
}
}
else
perror("Failed to execute command");
break;
case 'c': // case echo
if (strcmp(string, "echo") == 0)
{
if (arr[1][0] == '$')
{
char temp[100];
int c = 0;
for (int j = 1; arr[1][j] != '\0'; j++)
{
temp[c++] = arr[1][j];
}
temp[c] = '\0';
arr[1] = getenv(temp);
}
remove_quotes(arr[1]);
for (int j = 1; arr[j] != NULL; j++)
printf("%s\n", arr[j]);
}
else
perror("Failed to execute command");
break;
case 'x': // case export
if (strcmp(string, "export") == 0)
{
token = strtok(arr[1], "=");
char *name = token;
token = strtok(NULL, "=");
value = token;
setenv(name, value, 1);
}
else
perror("Failed to execute command");
break;
default:
perror("Failed to execute command");
shell();
}
}
// Executes external commands using fork and exec
void execute_command()
{
//fork a new process
pid_t pid = fork(); // child id
id = pid;
if (pid < 0) // Error
{
perror("Fork failed");
exit(EXIT_FAILURE);
}
else if (pid == 0) // In the child process
{
// Execute the command using execvp
if (execvp(arr[0], arr) == -1)
{
perror("Command not found!");
exit(EXIT_FAILURE);
}
else
execvp(arr[0], arr);
}
else // In the parent process
{
if (flag == 0)
on_child_exit(pid);
}
}
//handles child process termination and writes to log file
void on_child_exit(pid_t pid)
{
int status;
waitpid(pid, &status, 0);
write_to_log_file(pid);
}
//handles signal exit
void on_signal_exit()
{
int var;
int status;
var = waitpid(id, &status, 0);
if (var >= 0)
write_to_log_file(id);
}
// Writes information about terminated child processes to a log file
void write_to_log_file(pid_t pid)
{
file = fopen("/home/ranime/Desktop/Term6/OS/Labs/Lab1/logs.txt", "a");
fprintf(file, "Child process (%d) terminated\n", pid);
fclose(file);
}
// Removes quotes from a string
void remove_quotes(char *str)
{
char *dest = str;
while (*str)
{
if (*str != '"')
*dest++ = *str;
str++;
}
*dest = '\0';
}