-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththesh.c
More file actions
98 lines (92 loc) · 3.71 KB
/
Copy paththesh.c
File metadata and controls
98 lines (92 loc) · 3.71 KB
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
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
typedef struct cmd{
int redirect_in; /*Any stdin redirection? */
int redirect_out; /*Any stdout redirection? */
int redirect_append; /*Append stdout redirection? */
int background; /*Put process in background? */
int piping; /*Pipe prog1 into prog2? */
char *infile; /*Name of stdin redirect file */
char *outfile; /*Name of stdout redirect file */
char *argv1[10]; /*First program to exicute */
char *argv2[10]; /*Second program in pipe */
}TODO;
int cmdscan(char *cmdbuf, struct cmd *com);
int main(void){
char buffer[1024];
int fdin[2], fdout[2], fdpipe[2], inputfile, outputfile;
TODO info;
pid_t child;
pipe(fdin);
pipe(fdout);
while((gets(buffer) != NULL)){
if (cmdscan(buffer,&info)){
printf("Illegal Format: \n");
continue;
}
if(strcmp(info.argv1[0], "exit") == 0){
exit(0);
}
switch(child = fork()){
case -1:
perror("fork error\n");
exit(0);
case 0: //child
switch(child = fork()){
case -1:
perror("fork error\n");
exit(-1);
case 0: //grandchild
if(info.redirect_in){
inputfile = open(info.infile, O_RDONLY);
dup2(inputfile, STDIN_FILENO);
close(inputfile);
}
if(info.redirect_out == 1 && info.redirect_append == 0){
outputfile = open(info.outfile, (O_CREAT | O_WRONLY | O_TRUNC), 0664);
dup2(outputfile, STDOUT_FILENO);
close(outputfile);
}
if(info.redirect_out == 1 && info.redirect_append == 1){
outputfile = open(info.outfile, (O_CREAT | O_WRONLY | O_APPEND), 0664);
dup2(outputfile, STDOUT_FILENO);
close(outputfile);
}
if(info.piping){
pipe(fdpipe);
switch(child = fork()){
case -1:
perror("grandchild fork error\n");
exit(-1);
case 0: //great grandchild
close(fdpipe[1]);
dup2(fdpipe[0],STDIN_FILENO);
//close(fdpipe[0]);
execvp(info.argv2[0], info.argv2);
perror("grandchild exec failed\n");
exit(-1);
}
close(fdpipe[0]);
dup2(fdpipe[1],STDOUT_FILENO);
close(fdpipe[1]);
}
execvp(info.argv1[0],info.argv1);
perror("exec failed\n");
exit(-1);
}
if(!info.background){
waitpid(child,NULL,WCONTINUED);
}
else{
waitpid(child,NULL,WNOHANG);
}
exit(0);
}
waitpid(child,NULL,WCONTINUED);
}//exits the while loop
}