-
Notifications
You must be signed in to change notification settings - Fork 0
/
redirection.c
164 lines (133 loc) · 2.56 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/wait.h>
#include "shell.h"
#define MAX_BUFFER 1024
#define MAX_ARGS 64
#define SEPARATORS " \t\n"
int get_argc(char **args) {
int length = 0;
while (args[length] != NULL)
{
length++;
}
return length;
}
int redirect_output_truncate(char *file_name)
{
if (freopen(file_name, "w", stdout) != NULL)
{
return 1;
}
else
{
printf("output redirection failed\n");
return 0;
}
}
int redirect_output_append(char *file_name)
{
if (freopen(file_name, "a", stdout) != NULL)
{
return 1;
}
else
{
printf("output redirection failed\n");
}
}
int redirect_input(char *file_name)
{
if (freopen(file_name, "r", stdin) != NULL)
{
return 1;
}
else
{
printf("input redirection failed\n");
}
}
int check_redirection(char **args, int length) {
int i = 0;
while (i < length)
{
if (!strcmp(args[i], ">"))
{
redirect_output_truncate(args[i + 1]);
}
if (!strcmp(args[i], ">>"))
{
redirect_output_append(args[i + 1]);
}
if (!strcmp(args[i], "<"))
{
redirect_input(args[i + 1]);
}
i++;
}
}
int restore_io(FILE *og_in, FILE *og_out, FILE *in, FILE *out)
{
fclose(in);
fclose(out);
freopen(NULL, "r", og_in);
freopen(NULL, "w", og_out);
}
int main(int argc, char **argv) {
signal(SIGINT, signalhandler);
char buf[MAX_BUFFER];
char *args[MAX_ARGS];
char **arg;
FILE *original_stdout = freopen(NULL, "w", stdout);
FILE *original_stdin = freopen(NULL, "r", stdin);
FILE *fptr;
if (argv[1])
{
fptr = fopen(argv[1], "r");
}
else
{
fptr = stdin;
}
if (fptr == stdin)
{
printf("\033[2J\033[H");
printf(" **************************\n"
" * MY SHELL *\n"
" * *\n"
" * use at *\n"
" * own risk *\n"
" * *\n"
" **************************\n\n\n"
);
}
while(!feof(fptr))
{
if (fptr == stdin)
{
printf("%s", get_prompt());
}
if (fgets(buf, MAX_BUFFER, fptr))
{
if (strstr(buf, " &") != NULL)
{
execute_file(args, 0);
}
arg = args;
*arg++ = strtok(buf, SEPARATORS);
while ((*arg++ = strtok(NULL, SEPARATORS)));
check_redirection(args, get_argc(args));
/*
if (!run(tree, args)) {
execute_file(args ,1);
}
continue;
}
}*/
}
}
}