-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.c
132 lines (106 loc) · 3.5 KB
/
runner.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
#include "headers/runner.h"
//Executa comando simples
char* runSingle(char* cmd) {
int status,i=0,n=1;
char* token,*out,*command,*pipeCase,*pipeInput;
char* exec_args[16];
char buffer[128];
int pp[2],it=1;
pipe(pp);
command = cmd;
pipeCase = strstr(command,"|");
if (pipeCase) {
command[pipeCase-command] = '\0';
pipeInput = runSingle(command);
return runPiped(pipeInput,pipeCase+2);
}
token = strtok(command," ");
while(token!=NULL){
exec_args[i]=token;
token=strtok(NULL," ");
i++;
}
exec_args[i]=NULL;
if(!fork()){
close(pp[0]);
dup2(pp[1],1);
execvp(exec_args[0],exec_args);
perror("Erro ao executar");
_exit(1);
}
else{
wait(&status);
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) == 1) return NULL;
}
close(pp[1]);
n = read(pp[0],buffer,127);
buffer[n]='\0';
out = malloc(n+1);
strncpy(out,buffer,n);
if(n == 127) {
while(it) {
n = read(pp[0],buffer,127);
if(n == 0) break;
buffer[n] = '\0';
sprintf(out,"%s%s",out,buffer);
}
}
return out;
}
}
//Executa comando composto
char* runPiped(char* input, char* cmd) {
int status,i=0,n=1;
char* string,*out,*command,*pipeCase,*pipeInput;
char* exec_args[128],buffer[128];
int ppIn[2], ppOut[2];
pipe(ppIn);
pipe(ppOut);
command = cmd;
pipeCase = strstr(command,"|");
if (pipeCase) {
command[pipeCase-command] = '\0';
pipeInput = runPiped(input,command);
return runPiped(pipeInput,pipeCase+2);
}
string = strtok(command," ");
while(string!=NULL) {
exec_args[i]=string;
string=strtok(NULL," ");
i++;
}
exec_args[i]=NULL;
if(!fork()) {
close(ppIn[1]);
dup2(ppIn[0],0);
close(ppOut[0]);
dup2(ppOut[1],1);
execvp(exec_args[0],exec_args);
perror("Erro ao executar");
_exit(1);
}
else {
close(ppIn[0]);
write(ppIn[1], input, strlen(input));
close(ppIn[1]);
wait(&status);
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) == 1) return NULL;
}
close(ppOut[1]);
n = read(ppOut[0],buffer,128);
buffer[n]='\0';
out = malloc(n+1);
strcpy(out,buffer);
if(n == 128) {
while(n) {
n = read(ppOut[0],buffer,128);
if(n == 0) break;
buffer[n] = '\0';
sprintf(out,"%s%s",out,buffer);
}
}
return out;
}
}