forked from mtstickney/Pipeline-Sort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe_util.c
82 lines (72 loc) · 1.32 KB
/
pipe_util.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
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include "pipe_util.h"
#define NPROCS (elements+2)
extern char *get_name(FILE* f);
int mk_pipe(Pipe *p)
{
int fds[2];
int ret;
ret = pipe(fds);
p->reader = fds[0];
p->writer = fds[1];
return ret;
}
void close_pipe(Pipe *p)
{
close(p->reader);
close(p->writer);
}
int chain(char *path, char *args[], FILE *filters, unsigned int elements)
{
Pipe pipes[2];
Pipe *in, *out, *tmp;
unsigned int child;
in = &pipes[0];
out = &pipes[1];
for (child = 0; child < NPROCS; child++) {
if (child < NPROCS-1) {
if (mk_pipe(out) != 0) {
perror("begin");
return -1;
}
}
switch(fork()) {
case -1:
return -1;
case 0:
if (child > 0) {
dup2(in->reader, STDIN_FILENO);
close(in->reader);
close(in->writer);
}
if (child < NPROCS-1) {
dup2(out->writer, STDOUT_FILENO);
close(out->writer);
close(out->reader);
}
if (execv(path, args) == -1) {
perror("begin");
exit(1);
};
default:
if (child > 0)
close_pipe(in);
}
/* patch up arguments */
if (child == 0 || child >= elements) {
free(path);
path = get_name(filters);
if (path == NULL) {
fprintf(stderr, "begin: Unexpected end of filter list\n");
return -1;
}
args[0] = path;
}
tmp = in;
in = out;
out = tmp;
}
return 0;
}