Repository navigation
Expand file tree
/
Copy pathredirection.cpp
More file actions
133 lines (121 loc) · 3.47 KB
/
Copy pathredirection.cpp
File metadata and controls
133 lines (121 loc) · 3.47 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
#include "headers.h"
static string trimSpaces(const string &s)
{
size_t a = s.find_first_not_of(" \t");
if (a == string::npos)
return "";
size_t b = s.find_last_not_of(" \t");
return s.substr(a, b - a + 1);
}
// args is the redirection-tokenized command: [ "cmd args", "<"|">"|">>", file, ... ]
void redirection(vector<string> args)
{
int inputFd = -1;
int outputFd = -1;
vector<string> commandParts;
for (size_t i = 0; i < args.size(); ++i)
{
const string &tok = args[i];
if (tok == "<" || tok == ">" || tok == ">>")
{
if (i + 1 >= args.size())
{
cerr << "Syntax error: missing file name after '" << tok << "'" << endl;
if (inputFd != -1)
close(inputFd);
if (outputFd != -1)
close(outputFd);
return;
}
string fileName = trimSpaces(args[++i]);
if (tok == "<")
{
if (inputFd != -1)
close(inputFd);
inputFd = open(fileName.c_str(), O_RDONLY);
if (inputFd == -1)
{
cerr << "cannot open '" << fileName << "': " << strerror(errno) << endl;
if (outputFd != -1)
close(outputFd);
return;
}
}
else
{
int flags = O_WRONLY | O_CREAT | (tok == ">>" ? O_APPEND : O_TRUNC);
if (outputFd != -1)
close(outputFd);
outputFd = open(fileName.c_str(), flags, 0644);
if (outputFd == -1)
{
cerr << "cannot open '" << fileName << "': " << strerror(errno) << endl;
if (inputFd != -1)
close(inputFd);
return;
}
}
}
else
{
string part = trimSpaces(tok);
if (!part.empty())
commandParts.push_back(part);
}
}
vector<string> cmd;
for (const string &part : commandParts)
{
vector<string> t = tokenize(part);
cmd.insert(cmd.end(), t.begin(), t.end());
}
if (cmd.empty())
{
if (inputFd != -1)
close(inputFd);
if (outputFd != -1)
close(outputFd);
cerr << "Syntax error: no command to run" << endl;
return;
}
pid_t pid = fork();
if (pid == 0)
{
signal(SIGINT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
if (inputFd != -1)
{
dup2(inputFd, STDIN_FILENO);
close(inputFd);
}
if (outputFd != -1)
{
dup2(outputFd, STDOUT_FILENO);
close(outputFd);
}
char **argv = new char *[cmd.size() + 1];
for (size_t i = 0; i < cmd.size(); ++i)
{
argv[i] = new char[cmd[i].size() + 1];
strcpy(argv[i], cmd[i].c_str());
}
argv[cmd.size()] = nullptr;
execvp(argv[0], argv);
cerr << cmd[0] << ": command not found" << endl;
_exit(127);
}
else if (pid < 0)
{
perror("fork");
}
else
{
if (inputFd != -1)
close(inputFd);
if (outputFd != -1)
close(outputFd);
int status = 0;
while (waitpid(pid, &status, 0) == -1 && errno == EINTR)
;
}
}