-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredirect.cpp
More file actions
33 lines (31 loc) · 949 Bytes
/
redirect.cpp
File metadata and controls
33 lines (31 loc) · 949 Bytes
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
#include <vector>
#include <string>
#include <fcntl.h>
#include <unistd.h>
#include "tinyshell.h"
bool redirect_in(std::vector<std::string>& args) {
for (size_t i = 0; i < args.size(); ++i) {
if (args[i] == "<" && i + 1 < args.size()) {
int fd = open(args[i + 1].c_str(), O_RDONLY);
if (fd < 0) exit_error("open (in)");
dup2(fd, STDIN_FILENO);
close(fd);
erase_from(args, 2);
return true;
}
}
return true;
}
bool redirect_out(std::vector<std::string>& args) {
for (size_t i = 0; i < args.size(); ++i) {
if (args[i] == ">" && i + 1 < args.size()) {
int fd = open(args[i + 1].c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) exit_error("open (out)");
dup2(fd, STDOUT_FILENO);
close(fd);
erase_from(args, 2);
return true;
}
}
return true;
}