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


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

int main(void) {
    int fd1[2], fd2[2];   // fd1: родитель -> потомок, fd2: потомок -> родитель
    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(fd1) == -1 || pipe(fd2) == -1) {
        perror("pipe");
        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++) {
            read(fd1[0], question, sizeof(question));            // читаем вопрос
            printf("Child received: %s\n", question);
            write(fd2[1], answers[i], strlen(answers[i]) + 1);  // отправляем ответ (+1 для '\0')
        }
        close(fd1[0]);
        close(fd2[1]);
        exit(0);
    } else {
        /* Родитель: пишет вопросы в fd1, читает ответы из fd2 */
        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;
}