-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path44-1-pipe_echo.c
66 lines (61 loc) · 1.62 KB
/
44-1-pipe_echo.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
#include <unistd.h>
#include <ctype.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
int pfd1[2], pfd2[2];
if (pipe(pfd1) == -1)
errExit("pipe");
if (pipe(pfd2) == -1)
errExit("pipe");
printf("opne pipe on fd (%d, %d) and (%d, %d)\n", pfd1[0], pfd1[1], pfd2[0], pfd2[1]);
char buf[4096];
switch (fork())
{
case -1:
errExit("fork");
break;
case 0: // Child
if (close(pfd1[1]) == -1)
errExit("close");
if (close(pfd2[0]) == -1)
errExit("close");
while (1)
{
int read_num = read(pfd1[0], buf, 4096);
if (read_num == -1)
errExit("child read");
else if (read_num == 0)
break;
else
{
for (int i = 0; buf[i] != '\0' && i < read_num; i++)
buf[i] = toupper(buf[i]);
if (write(pfd2[1], buf, read_num) == -1)
errExit("write");
}
}
default: // parent
if (close(pfd1[0]) == -1)
errExit("close");
if (close(pfd2[1]) == -1)
errExit("close");
while (1)
{
fgets(buf, 4096, stdin);
if (write(pfd1[1], buf, strlen(buf) + 1) == -1)
errExit("write");
int read_num = read(pfd2[0], buf, 4096);
if (read_num == -1)
errExit("read");
else if (read_num == 0)
break;
else
{
printf("%s", buf);
}
}
break;
}
return 0;
}