-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIfCommand.cc
More file actions
78 lines (66 loc) · 1.5 KB
/
IfCommand.cc
File metadata and controls
78 lines (66 loc) · 1.5 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
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>
#include "Command.hh"
#include "SimpleCommand.hh"
#include "IfCommand.hh"
IfCommand::IfCommand() {
_condition = NULL;
_listCommands = NULL;
}
// Run condition with command "test" and return the exit value.
int
IfCommand::runTest(SimpleCommand * condition) {
std::vector<char*> args;
char *test = (char *)"test";
args.push_back(test);
for (auto &arg : condition->_arguments) {
args.push_back(const_cast<char*>(arg->c_str()));
}
args.push_back(nullptr);
pid_t ret = fork();
if (ret == -1) {
perror("bash fork");
return -1;
} else if (ret == 0) {
execvp(args[0], args.data());
perror("execvp");
exit(EXIT_FAILURE);
} else {
int status;
waitpid(ret, &status, 0);
return WEXITSTATUS(status);
}
args.clear();
condition->print();
return 0;
}
void
IfCommand::insertCondition( SimpleCommand * condition ) {
_condition = condition;
}
void
IfCommand::insertListCommands( ListCommands * listCommands) {
_listCommands = listCommands;
}
void
IfCommand::clear() {
}
void
IfCommand::print() {
printf("IF [ \n");
this->_condition->print();
printf(" ]; then\n");
this->_listCommands->print();
}
void
IfCommand::execute() {
// Run command if test is 0
if (runTest(this->_condition) == 0) {
_listCommands->execute();
}
}