-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
101 lines (84 loc) · 2.14 KB
/
main.cpp
File metadata and controls
101 lines (84 loc) · 2.14 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
#include "allFunctions.h"
pid_t pid = -1;
// Handles SIGINT signal by forwarding it to the foreground child process
void sigintHandler(int sig)
{
if (pid > 0)
{
kill(pid, SIGINT);
}
}
// Handles SIGTSTP signal by forwarding it to the foreground child process
void sigtstpHandler(int sig)
{
if (pid > 0)
{
kill(pid, SIGTSTP);
}
}
// Sets up signal handlers for SIGINT and SIGTSTP
void setupSignals()
{
signal(SIGINT, sigintHandler);
signal(SIGTSTP, sigtstpHandler);
}
// Main entry point that initializes the shell and runs the command loop
int main()
{
char start[4096];
if (!getcwd(start, sizeof(start)))
{
perror("getcwd");
return 1;
}
string homeDir = string(start);
struct passwd *pw = getpwuid(getuid());
string user = pw ? pw->pw_name : "user";
char hostbuf[256];
gethostname(hostbuf, sizeof(hostbuf));
string host = hostbuf;
ios::sync_with_stdio(false);
cin.tie(nullptr);
initHistory();
setupSignals();
setupAutocomplete();
while (true)
{
char cwdBuf[4096];
if (!getcwd(cwdBuf, sizeof(cwdBuf)))
strcpy(cwdBuf, "?");
string disp = tildeDisplay(cwdBuf, homeDir);
string prompt = user + "@" + host + ":" + disp + "$ ";
char *in = readline(prompt.c_str());
if (!in)
{
cout << "\nlogout\n";
break;
}
string line(in);
free(in);
if (all_of(line.begin(), line.end(),
[](unsigned char ch)
{ return isspace(ch); }))
continue;
add_history(line.c_str());
saveHistory();
vector<string> cmd = semicolonSplit(line);
for (auto &x : cmd)
{
vector<string> args = tokenize(x);
if (args.empty())
continue;
for (auto &a : args)
a = tildeExpand(a, homeDir);
if (args[0] == "exit")
{
saveHistory();
return 0;
}
executePipeline(args, homeDir);
}
}
saveHistory();
return 0;
}