-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredirection.cpp
More file actions
47 lines (46 loc) · 1.27 KB
/
redirection.cpp
File metadata and controls
47 lines (46 loc) · 1.27 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
#include "allFunctions.h"
// Processes and applies input/output redirections (<, >, >>) from the command
void handleRedirections(vector<string> &cmd)
{
for (int i = 0; i < cmd.size();)
{
if (cmd[i] == "<")
{
int fd = open(cmd[i + 1].c_str(), O_RDONLY);
if (fd < 0)
{
perror("open < failed");
exit(1);
}
dup2(fd, STDIN_FILENO);
close(fd);
cmd.erase(cmd.begin() + i, cmd.begin() + i + 2);
}
else if (cmd[i] == ">")
{
int fd = open(cmd[i + 1].c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0)
{
perror("open > failed");
}
dup2(fd, STDOUT_FILENO);
close(fd);
cmd.erase(cmd.begin() + i, cmd.begin() + i + 2);
}
else if (cmd[i] == ">>")
{
int fd = open(cmd[i + 1].c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd < 0)
{
perror("open >> failed");
}
dup2(fd, STDOUT_FILENO);
close(fd);
cmd.erase(cmd.begin() + i, cmd.begin() + i + 2);
}
else
{
i++;
}
}
}