-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.cpp
338 lines (291 loc) · 11.1 KB
/
shell.cpp
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
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <vector>
#include <string>
#include <sstream>
#include <cstring>
#include <termios.h>
#include <dirent.h>
#include "Tokenizer.h"
using namespace std;
// Define ANSI color codes for shell prompt styling.
#define RED "\033[1;31m"
#define GREEN "\033[1;32m"
#define YELLOW "\033[1;33m"
#define BLUE "\033[1;34m"
#define WHITE "\033[1;37m"
#define NC "\033[0m" // Reset color
// Function to get a list of files matching a given input string in the current directory
vector<string> getMatchingFiles(const string &input) {
vector<string> matches;
string dirPath;
string prefix;
size_t lastSlash = input.find_last_of('/');
if (lastSlash == string::npos) {
dirPath = ".";
prefix = input;
} else {
dirPath = input.substr(0, lastSlash);
prefix = input.substr(lastSlash + 1);
}
DIR *dir = opendir(dirPath.c_str());
if (dir) {
struct dirent *entry;
while ((entry = readdir(dir)) != nullptr) {
string fname = entry->d_name;
if (fname.find(prefix) == 0) {
matches.push_back(fname);
}
}
closedir(dir);
}
return matches;
}
// Variables for command history and index
vector<string> commandHistory;
int currentHistoryIndex = -1;
// Function to get a single character from the input (used for handling special keys)
int getkey() {
int character;
struct termios orig_term_attr;
struct termios new_term_attr;
tcgetattr(fileno(stdin), &orig_term_attr);
memcpy(&new_term_attr, &orig_term_attr, sizeof(struct termios));
new_term_attr.c_lflag &= ~(ECHO | ICANON);
tcsetattr(fileno(stdin), TCSANOW, &new_term_attr);
character = fgetc(stdin);
tcsetattr(fileno(stdin), TCSANOW, &orig_term_attr);
return character;
}
// Function to execute a single command
void executeCommand(const Command &cmd) {
// Fork to create a child process to execute the command.
pid_t pid = fork();
if (pid < 0) { // error checking
perror("fork");
exit(2);
}
if (pid == 0) {
// Child process: redirect input and output, and execute the command.
if (!cmd.in_file.empty()) {
int fd_in = open(cmd.in_file.c_str(), O_RDONLY);
if (fd_in < 0) {
perror("open");
exit(2);
}
dup2(fd_in, STDIN_FILENO);
close(fd_in);
}
if (!cmd.out_file.empty()) {
int fd_out = open(cmd.out_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd_out < 0) {
perror("open");
exit(2);
}
dup2(fd_out, STDOUT_FILENO);
close(fd_out);
}
// Convert arguments to a format suitable for execvp.
vector<char *> args;
for (const string &arg : cmd.args) {
args.push_back(const_cast<char *>(arg.c_str()));
}
args.push_back(nullptr);
// Execute the command.
execvp(args[0], &args[0]);
perror("execvp");
exit(2);
} else {
// Parent process: wait for the child to finish.
int status = 0;
waitpid(pid, &status, 0);
if (status > 1) {
exit(status);
}
}
}
int main() {
// Store the previous directory for the 'cd -' command.
string previousDir = "";
// Vector object to store background PIDs
vector<pid_t> backgroundProcessStore;
for (;;) {
// Initialize string to store command
string thisCommand = "";
// Get path to current working directory (CWD) and username
char buffer[256];
getcwd(buffer, sizeof(buffer));
// Get the current date/time, username
char *username = getlogin();
char timeBuf[80];
time_t currentTime = time(0);
struct tm tstruct = *localtime(¤tTime);
strftime(timeBuf, sizeof(timeBuf), "%b %d %H:%M:%S", &tstruct);
// Display the shell prompt with the current date/time, username, and current directory.
cout << GREEN << timeBuf << " " << username << ":" << BLUE << buffer << YELLOW << "$ " << NC;
// Get user input.
string input;
getline(cin, input);
// Handling background processes (&)
for(size_t i = 0; i < backgroundProcessStore.size();) {
int status;
if (waitpid(backgroundProcessStore[i], &status, WNOHANG) == backgroundProcessStore[i]) {
backgroundProcessStore.erase(backgroundProcessStore.begin() + i);
} else {
i++;
}
}
istringstream commandStream(input);
// Process commands separated by semicolons.
while (getline(commandStream, thisCommand, ';')) {
// Trim leading and trailing whitespace from the command.
thisCommand = thisCommand.substr(thisCommand.find_first_not_of(" "), thisCommand.find_last_not_of(" ") - thisCommand.find_first_not_of(" ") + 1);
if (thisCommand == "exit") {
// Exit the shell.
cout << RED << "Exiting shell..." << NC << endl;
return 0;
}
if (thisCommand.substr(0, 3) == "cd ") {
// Change directory using the 'cd' command.
string targetDir = thisCommand.substr(3);
if (targetDir == "-") {
if (previousDir == "") {
cerr << "No previous directory to change to." << endl;
continue;
}
targetDir = previousDir;
}
char currentDir[1024];
getcwd(currentDir, sizeof(currentDir));
previousDir = currentDir;
if (chdir(targetDir.c_str()) != 0) {
perror("cd");
}
continue;
}
// Tokenize the command.
Tokenizer tknr(thisCommand);
if (tknr.hasError()) {
// If there was an error in tokenization, continue to the next prompt.
continue;
}
// Execute the command(s).
if (tknr.commands.size() == 1) {
// Single command without piping
if (tknr.commands[0]->isBackground()) {
// Background process
pid_t pid = fork();
if (pid < 0) {
perror("fork");
exit(2);
}
if (pid == 0) {
// Child process
executeCommand(*tknr.commands[0]);
exit(0);
} else {
// Parent process: add PID to backgroundProcessStore
backgroundProcessStore.push_back(pid);
}
} else {
// Foreground process
executeCommand(*tknr.commands[0]);
}
} else {
// Multiple commands with piping
int prev_pipe_fd[2] = {-1, -1};
for (size_t i = 0; i < tknr.commands.size(); i++) {
int pipe_fd[2];
int in_fd = -1, out_fd = -1;
if (i != tknr.commands.size() - 1) {
if (pipe(pipe_fd) < 0) {
perror("pipe");
exit(2);
}
}
if (!tknr.commands[i]->in_file.empty()) {
in_fd = open(tknr.commands[i]->in_file.c_str(), O_RDONLY);
if (in_fd < 0) {
perror("open");
continue;
}
}
if (!tknr.commands[i]->out_file.empty()) {
out_fd = open(tknr.commands[i]->out_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (out_fd < 0) {
perror("open");
continue;
}
}
pid_t pid = fork();
if (pid < 0) { // error checking
perror("fork");
exit(2);
}
if (pid == 0) {
// Child process: redirect input and output, and execute the command.
if (in_fd != -1) {
dup2(in_fd, STDIN_FILENO);
close(in_fd);
} else if (prev_pipe_fd[0] != -1) {
dup2(prev_pipe_fd[0], STDIN_FILENO);
}
if (out_fd != -1) {
dup2(out_fd, STDOUT_FILENO);
close(out_fd);
} else if (i != tknr.commands.size() - 1) {
dup2(pipe_fd[1], STDOUT_FILENO);
}
if (prev_pipe_fd[0] != -1) {
close(prev_pipe_fd[0]);
}
if (prev_pipe_fd[1] != -1) {
close(prev_pipe_fd[1]);
}
if (pipe_fd[0] != -1) {
close(pipe_fd[0]);
}
if (pipe_fd[1] != -1) {
close(pipe_fd[1]);
}
// Convert arguments to a format suitable for execvp.
vector<char *> args;
for (const string &arg : tknr.commands[i]->args) {
args.push_back(const_cast<char *>(arg.c_str()));
}
args.push_back(nullptr);
// Execute the command.
execvp(args[0], &args[0]);
perror("execvp");
exit(2);
} else {
// Parent process: wait for the child to finish and manage pipes.
if (in_fd != -1) {
close(in_fd);
}
if (out_fd != -1) {
close(out_fd);
}
if (prev_pipe_fd[0] != -1) {
close(prev_pipe_fd[0]);
}
if (prev_pipe_fd[1] != -1) {
close(prev_pipe_fd[1]);
}
int status = 0;
waitpid(pid, &status, 0);
if (status > 1) {
exit(status);
}
prev_pipe_fd[0] = pipe_fd[0];
prev_pipe_fd[1] = pipe_fd[1];
}
}
}
}
}
return 0;
}