-
Notifications
You must be signed in to change notification settings - Fork 0
/
redirection.c
131 lines (124 loc) · 3.74 KB
/
redirection.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
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
#include "headers.h"
#include "functions.h"
void ResetStreams()
{
dup2(initSTDIN,STDIN_FILENO);
dup2(initSTDOUT,STDOUT_FILENO);
if(redirread)
{
redirread = 0;
dup2(initSTDIN,STDIN_FILENO);
close(fd1);
}
if(redirwrite)
{
redirwrite = 0;
dup2(initSTDOUT,STDOUT_FILENO);
close(fd2);
}
}
char* HandleRedirection(char* command)
{
char* NewCommand = (char *) malloc(MY_LEN* sizeof(char));
strcpy(NewCommand, " ");
char* token = strtok(command," \t");
if(debug) printf("Redir token = %s\n",token);
while (token != NULL)
{
if(!strcmp(token,"<"))
{
redirread = 1;
if(debug) printf("< detected\n");
char* inputfile = strtok(NULL," \t");
if(inputfile == NULL)
{
fprintf(stderr,"Inputfile for redirection not mentioned\n");
return NULL;
}
else
{
// do something
initSTDIN = dup(STDIN_FILENO);
fd1 = open(inputfile,O_RDONLY);
if(fd1 == -1)
{
fprintf(stderr,"File %s doesnt exist\n",inputfile);
return NULL;
}
if(dup2(fd1,STDIN_FILENO) == -1)
{
fprintf(stderr,"Could not redirect input to %s\n",inputfile);
return NULL;
}
}
}
else if(!strcmp(token,">"))
{
redirwrite = 1;
if(debug) printf("> detected\n");
char* writefile = strtok(NULL," \t");
if(writefile == NULL)
{
fprintf(stderr,"Writefile for redirection not mentioned\n");
return NULL;
}
else
{
// do something
initSTDOUT = dup(STDOUT_FILENO);
fd2 = open(writefile,O_WRONLY | O_TRUNC | O_CREAT , 0644);
if(fd2 == -1)
{
fprintf(stderr,"File %s doesnt exist\n",writefile);
return NULL;
}
if(dup2(fd2,STDOUT_FILENO) == -1)
{
fprintf(stderr,"Could not redirect output to %s\n",writefile);
return NULL;
}
else
{
if(debug) printf("New output file = %s\n",writefile);
}
}
}
else if(!strcmp(token,">>"))
{
redirwrite = 1;
if(debug) printf(">> detected\n");
char* appendfile = strtok(NULL," \t");
if(appendfile == NULL)
{
fprintf(stderr,"Appendfile for redirection not mentioned\n");
return NULL;
}
else
{
// do something
initSTDOUT = dup(STDOUT_FILENO);
fd2 = open(appendfile,O_WRONLY | O_APPEND| O_CREAT, 0644);
if(fd2 == -1)
{
fprintf(stderr,"File %s doesnt exist\n",appendfile);
return NULL;
}
if(dup2(fd2,STDOUT_FILENO) == -1)
{
fprintf(stderr,"Could not redirect output to %s\n",appendfile);
return NULL;
}
}
}
else
{
if (debug) printf("Catting %s \n",token);
strcat(NewCommand, " ");
strcat(NewCommand,token);
strcat(NewCommand, " ");
}
token = strtok(NULL," \t");
}
if(debug) printf("Redir handler returning %s \n",NewCommand);
return NewCommand;
}