-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.cpp
More file actions
123 lines (103 loc) · 3.33 KB
/
main.cpp
File metadata and controls
123 lines (103 loc) · 3.33 KB
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
#include "src/command.h"
#include "src/executor.h"
#include "src/history.h"
#include <csignal>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include <termios.h>
using namespace std;
pid_t childPID = -1;
void handleSignal(int signal) {
if (childPID > 0) {
switch (signal) {
case SIGINT:
cout << "\nCTRL+C pressed\n";
kill(childPID, signal);
break;
case SIGTSTP:
cout << "\nCTRL+Z pressed\n";
kill(childPID, signal);
break;
default:
cout << "\nSignal not implemented: " << signal << "\n";
break;
}
}
}
std::string readCommandLine(const std::string &prompt, History &history) {
std::string cmd;
char c;
const int BACKSPACE = 127;
while (true) {
if (read(STDIN_FILENO, &c, 1) == 1) {
if (c == '\n') {
break;
} else if (c == BACKSPACE || c == '\b') {
if (!cmd.empty()) {
cmd.pop_back();
history.updateCommandLine(prompt, cmd); }
} else if (c == '\033') {
char seq[2];
if (read(STDIN_FILENO, &seq[0], 1) == 1 && read(STDIN_FILENO, &seq[1], 1) == 1) {
if (seq[0] == '[') {
if (seq[1] == 'A') {
cmd = history.getHistoryCommand(true);
history.updateCommandLine(prompt, cmd);
} else if (seq[1] == 'B') {
cmd = history.getHistoryCommand(false);
history.updateCommandLine(prompt, cmd);
}
}
}
continue;
} else {
cmd += c;
}
}
}
return cmd;
}
int main() {
Command commandParser;
Executor executor;
History history;
signal(SIGINT, handleSignal);
signal(SIGTSTP, handleSignal);
history.loadHistory();
const std::string prompt = "nutshell> ";
std::string cmd;
while (true) {
std::cout << prompt << std::flush;
cmd = readCommandLine(prompt, history);
if (cmd.empty()) continue;
if (cmd == "exit") break;
history.addToHistory(cmd);
if (cmd.compare("steve") == 0) {
if (executor.getStoppedJobsSize() > 0) {
std::vector<pid_t> stoppedJobs = executor.getStoppedJob();
for (int i = 0; i < stoppedJobs.size(); i++) {
if (i == stoppedJobs.size() - 1) {
cout << "[" << i + 1 << "]+ Stopped process " << stoppedJobs[i] << "\n";
break;
} else {
cout << "[" << i + 1 << "]- Stopped process " << stoppedJobs[i] << "\n";
}
}
} else {
cout << "No stopped jobs\n";
}
continue;
}
ParsedCommand parsedCmd = commandParser.parse(cmd);
if (!parsedCmd.isEmpty) {
cout << "\n";
executor.execute(parsedCmd, childPID);
history.saveHistory();
history.resetHistoryIterator();
}
}
return 0;
}