-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredirect.c
97 lines (91 loc) · 1.69 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
87
88
89
90
91
92
93
94
95
96
97
#include "headers.h"
void redirection(char token[200][200], int len)
{
char infile[100], outfile[100], appendfile[100];
int err = 0;
char *commmand[100];
len++;
for (int i = 0; i < len; ++i)
{
commmand[i] = token[i];
}
commmand[len] = NULL;
int pid, inpflag = 0, outflag = 0, appflag = 0;
int prev = 0;
pid = fork();
if (pid==0)
{
setpgid(getpid(),10);
signal(SIGINT, SIG_IGN);
for (int i = 0; i < len; ++i)
{
if (strcmp(commmand[i], ">>") == 0)
{
strcpy(appendfile, commmand[i + 1]);
commmand[i] = NULL;
appflag = 1;
}
else if (strcmp(commmand[i],"<") == 0)
{
strcpy(infile, commmand[i + 1]);
commmand[i] = NULL;
inpflag = 1;
}
else if(strcmp(commmand[i], ">") == 0)
{
strcpy(outfile, commmand[i + 1]);
commmand[i] = NULL;
outflag = 1;
}
}
if(inpflag == 1)
{
int fin;
fin = open(infile,O_RDONLY);
if (fin<0)
{
perror("Could not open input file");
exit(0);
}
dup2(fin,0);
close(fin);
}
if (outflag == 1)
{
int fout;
fout = open(outfile, O_CREAT|O_WRONLY | O_TRUNC, 0644);
if (fout<0)
{
perror("Could not open output file");
exit(0);
}
dup2(fout,1);
close(fout);
}
if (appflag == 1)
{
int fapp;
fapp = open(appendfile, O_CREAT | O_APPEND | O_WRONLY, 0644);
if (fapp<0)
{
perror("Could not open output file"); exit(0);
}
dup2(fapp,1);
close(fapp);
}
if (execvp(commmand[0],commmand)<0)
{
err = 1;
printf("%s: Command doesn't exist\n", commmand[0]);
}
}
else
{
int status;
while(waitpid(pid,&status,0) > 0);
}
if(err)
{
printf("%s with process id: %d exited normally\n",commmand[0],pid);
}
}