-
Notifications
You must be signed in to change notification settings - Fork 0
/
ptee.c
62 lines (49 loc) · 1000 Bytes
/
ptee.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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char const *argv[])
{
int i;
int *outputs = (int *) malloc(sizeof(int) * argc);
outputs[0] = STDOUT_FILENO;
for (i = 1; i < argc; i++) {
int pipefd[2];
pipe(pipefd);
int pid = fork();
if (pid < 0) {
fprintf(stderr, "%s: fork: %s\n", argv[0], strerror(errno));
exit(1);
}
if (pid == 0) {
dup2(pipefd[0], STDIN_FILENO);
char *args[4] = {"/bin/sh", "-c", (char *) argv[i], NULL};
execvp("/bin/sh", args);
} else {
close(pipefd[0]);
outputs[i] = pipefd[1];
}
}
while (1) {
char buf[8192];
ssize_t ret = read(STDIN_FILENO, buf, sizeof(buf));
if (ret < 0) {
perror("read");
exit(1);
}
for (i = 0; i < argc; i++) {
int len = ret;
char *bufp = buf;
while (len) {
int wret = write(outputs[i], bufp, len);
if (wret < 0) {
perror("write");
exit(1);
}
len -= wret;
bufp += wret;
}
}
}
return 0;
}