-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheshell.cpp
More file actions
137 lines (116 loc) · 3.99 KB
/
eshell.cpp
File metadata and controls
137 lines (116 loc) · 3.99 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <cstring>
#include <vector>
#include <string>
#include <sstream>
#include "parser.h"
using namespace std;
int main() {
string input;
parsed_input pinput;
pid_t pid;
int status;
bool quit = false;
while (!quit) {
cout << "/> ";
getline(cin, input);
istringstream iss(input);
string command;
vector<pid_t> children;
while (getline(iss, command, ';')) {
istringstream iss2(command);
string subcommand;
while (getline(iss2, subcommand, ',')) {
if (!parse_line(const_cast<char*>(subcommand.c_str()), &pinput)) {
cerr << "Invalid input" << endl;
continue;
}
//pretty_print(&pinput);
if (pinput.inputs[0].type == INPUT_TYPE_SUBSHELL) {
// Handle subshell execution
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
execl("/bin/sh", "sh", "-c", pinput.inputs[0].data.subshell, (char *)NULL);
perror("execl"); // execl returns only on error
exit(EXIT_FAILURE);
} else {
// Parent process
waitpid(pid, &status, 0);
}
} else {
if (pinput.num_inputs == 0) {
continue;
}
if (strcmp(pinput.inputs[0].data.cmd.args[0], "quit") == 0) {
quit = true;
break;
}
int n = pinput.num_inputs;
int pipefd[n - 1][2];
for (int i = 0; i < n; i++) {
if (i < n - 1) {
if (pipe(pipefd[i]) < 0) {
perror("pipe");
exit(EXIT_FAILURE);
}
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
else if (pid == 0) {
if (i > 0) {
if (dup2(pipefd[i - 1][0], 0) < 0) {
perror("dup2");
exit(EXIT_FAILURE);
}
}
if (i < n - 1) {
if (dup2(pipefd[i][1], 1) < 0) {
perror("dup2");
exit(EXIT_FAILURE);
}
}
for (int j = 0; j < i; j++) {
close(pipefd[j][0]);
close(pipefd[j][1]);
}
single_input* sput = &pinput.inputs[i];
char **para = sput->data.cmd.args;
if (execvp(para[0], para) < 0) {
perror("execvp");
exit(EXIT_FAILURE);
}
}
else {
if (i > 0) {
close(pipefd[i - 1][0]);
}
if (i < n - 1) {
close(pipefd[i][1]);
}
children.push_back(pid);
}
}
}
free_parsed_input(&pinput);
}
if (quit) break;
for (size_t i = 0; i < children.size(); i++) {
waitpid(children[i], &status, 0);
}
children.clear();
}
}
return 0;
}