最近在学习OSTEP这本书,留个课后习题笔记。

Homework(code):

chapter cpu-api

8. Write a program that creates two children, and connects the standard output of one to the standard input of the other, using the pipe() system call.

Code:

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
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main()
{
int pi[2];
int p = pipe(pi); // create pipe
if (p < 0)
{
fprintf(stderr, "pipe failed");
exit(1);
}
int rc[2];
for (int i = 0; i < 2; ++i)
{
rc[i] = fork(); // create child process
char *buf;
if (rc[i] < 0)
{
fprintf(stderr, "fork failed");
exit(1);
}
else if (rc[i] == 0)
{
switch (i)
{
case 0:
// child process 0
buf = "inputs...";
write(pi[1], buf, strlen(buf));
return 0;
case 1:
// child process 1
buf = malloc(20);
memset(buf, 0, 20);
read(pi[0], buf, 20);
printf("child1 read from child0 through pipe:\n(%s)\n", buf);
return 0;
}
break;
}
}
waitpid(rc[0], NULL, 0);
waitpid(rc[1], NULL, 0);
return 0;
}

参考了一下网络上的题解,原代码感觉不是很优雅,用了不建议使用的函数,于是理解原理后,改写了一个比较优雅的版本。