#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
int fd1[2], fd2[2];
pid_t pid;
char question[50], answer[50];
int i;
const char *questions[] = {
"What is your name?",
"How old are you?",
"Bye!"
};
const char *answers[] = {
"Pipe Master",
"2 milliseconds",
"Goodbye!"
};
// fd1: родитель -> потомок
if (pipe(fd1) == -1)
{
perror("pipe");
exit(1);
}
// fd2: потомок -> родитель
if (pipe(fd2) == -1)
{
perror("pipe");
exit(1);
}
pid = fork();
if (pid == -1)
{
perror("fork");
exit(1);
}
if (pid == 0)
{
// Потомок
close(fd1[1]); // не пишет в первый канал
close(fd2[0]); // не читает второй канал
for (i = 0; i < 3; i++)
{
// читаем вопрос
read(fd1[0], question, sizeof(question));
printf("Child received: %s\n", question);
// отправляем ответ
write(fd2[1], answers[i], strlen(answers[i]) + 1);
}
close(fd1[0]);
close(fd2[1]);
exit(0);
}
else
{
// Родитель
close(fd1[0]); // не читает первый канал
close(fd2[1]); // не пишет второй канал
for (i = 0; i < 3; i++)
{
// отправляем вопрос
write(fd1[1], questions[i], strlen(questions[i]) + 1);
// получаем ответ
read(fd2[0], answer, sizeof(answer));
printf("Parent got: %s\n", answer);
}
close(fd1[1]);
close(fd2[0]);
wait(NULL);
}
return 0;
}