-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredirect.c
86 lines (76 loc) · 1.42 KB
/
redirect.c
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
#include "redirect.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "argv.h"
#include "input.h"
void do_redirect(char* argv[]) {
int n = 0, fd;
/* < */
n = search_argv(argv, "<");
if (n > 0) {
/* file only */
fd = open(argv[n + 1], O_RDONLY);
if (fd < 0) {
perror(argv[n + 1]);
exit(1);
}
close(0);
dup2(fd, 0);
close(fd);
delete_argv(argv, n, 2);
}
/* > */
/* 1> */
n = search_argv(argv, ">");
if (!n) {
n = search_argv(argv, "1>");
}
if (n > 0) {
printf(">\n");
/* file only */
fd = open(argv[n + 1], O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
perror(argv[n + 1]);
exit(1);
}
close(1);
dup2(fd, 1);
close(fd);
delete_argv(argv, n, 2);
}
/* 2> */
n = search_argv(argv, "2>");
if (n > 0) {
printf("2>\n");
/* file only */
fd = open(argv[n + 1], O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
perror(argv[n + 1]);
exit(1);
}
close(2);
dup2(fd, 2);
close(fd);
delete_argv(argv, n, 2);
}
/* 2>&1 */
n = search_argv(argv, "2>&1");
if (n > 0) {
printf("2>&1\n");
/* file only */
fd = open(argv[n + 1], O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
perror(argv[n + 1]);
exit(1);
}
close(1);
close(2);
dup2(fd, 1);
dup2(fd, 2);
close(fd);
delete_argv(argv, n, 2);
}
}