-
Notifications
You must be signed in to change notification settings - Fork 0
/
dup_fd.c
79 lines (77 loc) · 1.42 KB
/
dup_fd.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
#include "headers.h"
#include "dup_fd.h"
int dup_fd_out(char *fname, char mode)
{
int fd;
if (mode == 'n')
{
fd = open(fname, O_CREAT | O_RDWR | O_TRUNC, 0644);
}
else
{
fd = open(fname, O_CREAT | O_RDWR | O_APPEND, 0644);
}
if (fd < 0)
{
printf("> invalid filename \n");
return -1;
}
int restore_fd = dup(STDOUT_FILENO);
if (restore_fd < 0)
{
printf("> redirection error \n");
return -1;
}
int cur_fd = dup2(fd, STDOUT_FILENO);
if (cur_fd < 0)
{
printf("> redirection error \n");
return -1;
}
return restore_fd;
}
int dup_fd_in(char *fname)
{
int fd = open(fname, O_CREAT | O_RDWR);
if (fd < 0)
{
printf("< invalid filename \n");
return -1;
}
int restore_fd = dup(STDIN_FILENO);
if (restore_fd < 0)
{
printf("< redirection error \n");
return -1;
}
int cur_fd = dup2(fd, STDIN_FILENO);
if (cur_fd < 0)
{
printf("< redirection error \n");
return -1;
}
return restore_fd;
}
int restore_fd(int fd, char mode)
{
int r1;
if (fd <= 0)
{
return fd;
}
if (mode == 'o')
{
r1 = dup2(fd, STDOUT_FILENO);
}
else
{
r1 = dup2(fd, STDIN_FILENO);
}
if (r1 < 0)
{
printf("< restore error \n");
return -1;
}
close(fd);
return r1;
}