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

static int write_all(int fd, const char *data, size_t length) {
    while (length > 0) {
        ssize_t n = write(fd, data, length);
        if (n < 0 && errno == EINTR) continue;
        if (n <= 0) { perror("write"); return -1; }
        data += n;
        length -= (size_t)n;
    }
    return 0;
}

int main(void) {
    int fd[2];
    if (pipe(fd) == -1) { perror("pipe"); return EXIT_FAILURE; }

    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        close(fd[0]);
        close(fd[1]);
        return EXIT_FAILURE;
    }

    if (pid == 0) {
        close(fd[1]); /* 子进程不用写端。 */
        char buf[128];
        puts("[子进程] 等待读取管道数据...");
        for (;;) {
            ssize_t n = read(fd[0], buf, sizeof(buf) - 1);
            if (n < 0 && errno == EINTR) continue;
            if (n < 0) {
                perror("read");
                close(fd[0]);
                return EXIT_FAILURE;
            }
            if (n == 0) break;
            buf[n] = '\0';
            printf("[子进程] 收到: %s", buf);
        }
        puts("[子进程] 读到 EOF，通信结束");
        close(fd[0]);
        return EXIT_SUCCESS;
    }

    close(fd[0]); /* 父进程不用读端。 */
    const char *msg = "Hello from parent via anonymous pipe!\n";
    printf("[父进程] 写入: %s", msg);
    int result = write_all(fd[1], msg, strlen(msg));
    close(fd[1]); /* 释放最后一个写端；读空后 read() 返回 0。 */

    int status;
    while (waitpid(pid, &status, 0) == -1) {
        if (errno == EINTR) continue;
        perror("waitpid");
        return EXIT_FAILURE;
    }
    if (result == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
        return EXIT_FAILURE;
    puts("[父进程] 子进程已结束");
    return EXIT_SUCCESS;
}
