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