Загрузка данных


// chat_template.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    int fd[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!"
    };

    if (pipe(fd) == -1) {
        perror("pipe");
        exit(1);
    }

    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(1);
    }

    if (pid == 0) {
        /* Потомок: читает вопросы, печатает и отправляет ответы */
        close(fd[1]); // потомок только читает, значит закрывает запись

        for (i = 0; i < 3; i++) {
            // TODO: прочитать вопрос от родителя в question
            // read(fd[0], question, sizeof(question));
            printf("Child received: %s\n", question);
            // TODO: отправить ответ обратно
            // write(fd[1], answers[i], strlen(answers[i])+1);
        }
        close(fd[0]);
        exit(0);
    } else {
        /* Родитель: отправляет вопросы и читает ответы */
        close(fd[0]); // родитель только пишет, закрывает чтение

        for (i = 0; i < 3; i++) {
            // TODO: отправить вопрос потомку
            // write(fd[1], questions[i], strlen(questions[i])+1);
            // TODO: прочитать ответ от потомка
            // read(fd[0], answer, sizeof(answer));
            printf("Parent got: %s\n", answer);
        }
        close(fd[1]);
        wait(NULL);
    }
    return 0;
}