-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipes.c
109 lines (79 loc) · 2.25 KB
/
pipes.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
#include "headers.h"
#include "string.h"
#include "handle.h"
#include <sys/types.h>
#include <sys/wait.h>
#include"pipes.h"
#include"parse.h"
#include"redir.h"
int is_inbuilt(char *cmd){
char *inbuilts[] = {"echo","cd","pwd","ls","pinfo","jobs","quit","fg","bg","kjob","overkill","setenv","unsetenv"};
for(int i = 0; i < 7; i++){
if(strcmp(cmd,inbuilts[i]) == 0){
return 1;
}
}
return 0;
}
void piping_main(struct op pipe_structure){
int my_pipes[2],pid;
int input_fd = STDIN_FILENO;
struct op cur;
for(int i = 0;i<pipe_structure.n-1;i++){
if(pipe(my_pipes) == -1){
perror("pipe: ");
}
cur = parse_commands(pipe_structure.list[i]," ");
cur.list[cur.n] = NULL;
create_child(input_fd,my_pipes[1],cur.n,cur.list);
close(my_pipes[1]);
free(cur.list);
input_fd = my_pipes[0];
}
cur = parse_commands(pipe_structure.list[pipe_structure.n-1]," ");
cur.list[cur.n] = NULL;
create_child(input_fd,STDOUT_FILENO,cur.n,cur.list);
}
void create_child(int input_fd,int output_fd,int argc,char **argv){
int pid,*status;
pid = fork();
if(pid < 0){
perror("");
}
else if(pid == 0){
if(input_fd != STDIN_FILENO){
dup2(input_fd,STDIN_FILENO);
close(input_fd);
}
if(output_fd != STDOUT_FILENO){
dup2(output_fd,STDOUT_FILENO);
close(output_fd);
}
status = is_redir(argc,argv); //checking redirection
if(status[0] > 0){
argv[status[1]] = NULL;
handle_redirection();
if(perform_redirection() == 0){
exit(0);
}
}
if(status[0] >= 0){
if(is_inbuilt(argv[0])){
handle_commands(status[1],argv);
}
else
{
if(execvp(argv[0],argv)==-1){
perror(argv[0]);
}
}
}
else{
printf("Wrong syntax \n");
}
exit(0);
}
else{
wait(NULL);
}
}