-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell_main.cpp
86 lines (73 loc) · 1.76 KB
/
shell_main.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
#include <iostream>
#include <string>
#include <sstream>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
int main()
{
string input;
while (true)
{
cout << "$ ";
getline(cin, input);
istringstream iss(input);
string command;
iss >> command;
if (command == "exit")
{
exit(1);
}
else if (command == "print")
{
cout << "Current PID: " << getpid() << endl;
}
else if (command == "help")
{
cout << "Available commands:" << endl;
cout << " exit - Terminate the shell" << endl;
cout << " print - Print the current PID" << endl;
cout << " help - Display this help information" << endl;
}
else if (command == "")
continue;
else
{
// Execute an external command
pid_t pid = fork();
if (pid == 0)
{
// Child process
// Convert the command string to a C string
char *cmd = const_cast<char *>(command.c_str());
// Convert the arguments to an array of C strings
int i = 0;
char *args[100];
args[i++] = cmd;
string arg;
while (iss >> arg && i < 100)
{
args[i++] = const_cast<char *>(arg.c_str());
}
args[i] = nullptr;
// Execute the command
execvp(cmd, args);
// If execvp returns, it must have failed
cout << "Command not found: " << command << endl;
exit(EXIT_FAILURE);
}
else if (pid > 0)
{
// Parent process
int status;
waitpid(pid, &status, 0);
}
else
{
// Failed to fork
cout << "Failed to fork" << endl;
}
}
}
return 0;
}