通過管道連線兩個子程序
通過管道連線兩個子程序是通過將兩個子程序通過同一個管道的不同端連線到父程序來執行的。通常,父母不會參與孩子之間的對話,因此它會關閉兩個管道末端的副本。
int demo() {
int pipefds[2];
pid_t child1, child2;
if (pipe(pipefds)) {
// error - abort ...
}
switch (child1 = fork()) {
case -1:
// error - abort
break;
case 0: /* child 1 */
close(pipefds[0]);
write(pipefds[1], "Hello, brother!", 15);
exit(0);
default: /* parent */
// nothing
}
switch (child1 = fork()) {
case -1:
// error - abort
break;
case 0: /* child 2 */
char buffer[256];
ssize_t nread;
close(pipefds[1]);
nread = read(pipefds[0], buffer, sizeof(buffer) - 1);
if (nread < 0) {
// handle error
} else {
buffer[nread] = '\0';
printf("My brother told me '%s'\n", buffer);
}
exit(0);
default: /* parent */
// nothing
}
// Only the parent reaches this point
close(pipefds[0]);
close(pipefds[1]);
if (child1 >= 0) {
wait(NULL);
if (child2 >= 0) {
wait(NULL);
}
}
}