-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
96 lines (83 loc) · 2.53 KB
/
main.cpp
File metadata and controls
96 lines (83 loc) · 2.53 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
#include <vector>
#include <sys/wait.h>
#include <iostream>
#include <cstring>
#include "parser.h"
#include "cd.h"
#include "history.h"
#include <cstdio>
#include "preParser/preParser.h"
#include "redirect/redirect.h"
using namespace std;
int main()
{
History h = History();
while (true)
{
cout << "Welcome to MiniShell>" << endl;
string input;
getline(cin, input);
if (input == "exit")
{
break;
}
vector<Chain> chainCommands = parseCommands_accTo_op(input);
int lastExitCode = 0;
for (Chain &c : chainCommands)
{
vector<char *> args = parseInput(c.commands);
h.addCmdtoHistory(args[0]);
if (strcmp(args[0], "cd") == 0)
{
handle_cd_cmd(args);
freeArgs(args);
if(c.op == "||") break;
lastExitCode = 0;
continue;
}
else if (strcmp(args[0], "history") == 0)
{
h.printHistory();
freeArgs(args);
if(c.op == "||") break;
lastExitCode = 0;
continue;
}
pid_t pid = fork();
if (pid < 0)
{
perror("Fork failed");
freeArgs(args);
lastExitCode = 1;
// exit(1);
}
else if (pid == 0)
{
bool res = handle_redirection(args);
if(!res){
perror("Redirection failed");
freeArgs(args);
exit(1);
}
//cout << "Child process with parent pid " << getppid() << " and pid " << getpid() << " with command : " << args[0] << endl;
if (execvp(args[0], args.data()) == -1)
{
perror("Error executing command");
freeArgs(args);
exit(1); //this sets the exit status to 1 , and the parent collects the exit status of the child as 1.
}
}
else
{
//cout << "Parent process" << getpid() << endl;
int status;
waitpid(pid , &status , 0);
lastExitCode = WEXITSTATUS(status);
freeArgs(args);
}
if(c.op == "&&" && lastExitCode != 0) break;
if(c.op == "||" && lastExitCode == 0) break;
}
}
exit(0);
}