-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpleShell.cpp
More file actions
173 lines (136 loc) · 3.24 KB
/
simpleShell.cpp
File metadata and controls
173 lines (136 loc) · 3.24 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
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
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <sstream>
#include <cstdlib>
#include <unistd.h>
#include <sys/wait.h>
#include <dirent.h>
#include <cstring>
using namespace std;
bool executeBuiltin(vector<string> arg)
{
if (arg.empty())
return 0;
if (arg[0] == "exit")
{
int exitCode = (arg.size() > 1 && isdigit(arg[1][0])) ? stoi(arg[1]) : 0;
exit(exitCode);
}
if (arg[0] == "echo")
{
for (int i = 1; i < arg.size(); i++)
{
cout << arg[i] << " ";
}
cout << endl;
return 1;
}
if (arg[0] == "type" and arg.size() > 1)
{
for (int i = 1; i < arg.size(); i++)
{
if (arg.size() > 1 and (arg[i] == "type" or arg[i] == "exit" or arg[i] == "echo"))
{
cout << arg[i] << " is shell builtin command " << endl;
}
else
{
bool flag = 0;
string path = getenv("PATH");
stringstream ss(path);
string dir;
while (getline(ss, dir, ':'))
{
DIR *dp = opendir(dir.c_str());
if (!dp)
continue;
struct dirent *entry;
while ((entry = readdir(dp)) != nullptr )
{
if (entry->d_name == arg[i])
{
cout << arg[i] << " is " << dir << " " << arg[i] << endl;
flag = 1;
break;
}
}
closedir(dp);
if (flag)
break;
}
if(!flag){
cout<<arg[i]<<" not found"<<endl;
}
}
}
return 1;
}
return 0 ;
}
vector<string> splitCommand(string command)
{
vector<string> arg;
stringstream ss(command);
string word;
while (ss >> word)
{
arg.push_back(word);
}
return arg;
}
void executeExternal(vector<string> arg){
if(arg.empty()) return ;
pid_t pid = fork();
if(pid==-1){
cout<<"Fork Failed"<<endl;
return;
}
// child Process
if(pid==0){
vector<char *> c_args;
for(auto k: arg) {
c_args.push_back(&k[0]);
}
c_args.push_back(nullptr);
execvp(c_args[0],c_args.data());
perror("Command execution failed");
exit(1);
}
else{
int status;
waitpid(pid,&status,0);
}
}
void shellLoop()
{
while (1)
{
cout << "$";
cout.flush();
string command;
if (!getline(cin, command) || command == "exit")
{
break;
}
vector<string> arg = splitCommand(command);
for (int i = 0; i < arg.size(); i++)
{
cout << arg[i] << " ";
}
cout << endl;
if (arg.empty())
continue;
if (executeBuiltin(arg))
{
continue;
}
executeExternal(arg);
}
}
int main()
{
shellLoop();
cout << "hheee";
return 0;
}