-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspawn.c
120 lines (84 loc) · 2.5 KB
/
spawn.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
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "includes/globals.h"
#include "includes/readLine.h"
int main(int argc, char** argv) {
if (argc < 2) {
return EXIT_FAILURE;
}
/* array para onde se vai ler os argumentos que tem $ na frente */
long input[128];
char* end;
long read;
/* array que guarda o i de argv[i] onde os $ vao sendo encontrados */
int* positions = malloc(sizeof(int)*1);
/* conta o numero de argumentos que leu */
int nread = 0;
/* ciclo que que le os argumentos com $ na frente e os passa para um array input. O i do argv[i]
fica guardado no array positions */
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '$') {
read = strtol(&(argv[i][1]), &end, 10);
if (read == 0 && errno == 0) {
fprintf(stderr, "Error reading arguments: %s\n", strerror(errno));
}
else {
input[nread] = read;
*(positions+nread) = i;
nread++;
positions = realloc(positions,sizeof(int)*1);
}
}
}
// Ler linhas do stdin
char buffer[PIPE_BUF];
char* columnValue = malloc(PIPE_BUF);
ssize_t i;
while ( (i = readLine(0, buffer, (long) PIPE_BUF)) > 0) {
int counter = 0;
// Ciclo que obtem os valores das colunas que o argumento da funcao manda ler
for(int i = 0; i < nread; i++) {
if (getElementValue(buffer, input[i], &columnValue[i], (long) PIPE_BUF) < 1) {
fprintf(stderr, "(filter) Error obtaining column values (getElementValue returned 0)");
return EXIT_FAILURE;
}
else {
strcpy(argv[*(positions+counter)], &columnValue[i]); // copia o valor que esta na coluna para o argv
counter++;
}
}
char *output = malloc(PIPE_BUF);
int exitStatus;
int result;
pid_t childId = fork(); // cria 1 processo filho
if (childId == 0) {
execvp(argv[1], &argv[1]); // executa os argumentos ja manipulados
exit(0);
}
while (wait(&exitStatus) > 0) {
result = WEXITSTATUS(exitStatus);
}
/* coloca o resultado do exec, p.e. --> input: a:3:x:2, output a:3:x:2:0 */
sprintf(output, "%d", result);
buffer[i - 1] = ':';
buffer[i] = '\0';
strcat(buffer, output);
ssize_t newLength = i + strlen(output);
buffer[newLength] = '\n';
buffer[newLength + 1] = '\0';
newLength++;
write(1, buffer, newLength);
}
if (i < 0) {
fprintf(stderr, "(filter) Error reading input: %s (read() returned %ld)\n", strerror(errno), i);
return EXIT_FAILURE;
} else {
return EXIT_SUCCESS;
}
}