编辑代码

#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>

int func(int pipefd[]) {
    char buffer[128];

    // 创建子进程
    pid_t pid;
    pid = fork();
    
    if (pid == -1) {
        perror("fork");
        return 1;
    }
    
    if (pid == 0) {  // 子进程
        close(pipefd[1]);  // 关闭写端

        // 从管道读取数据
        ssize_t count = read(pipefd[0], buffer, sizeof(buffer));
        if (count == -1) {
            perror("read");
            return 1;
        }

        buffer[count] = '\0';  // 确保字符串以 '\0' 结尾
        std::cout << "Child process received: " << buffer << std::endl;

        close(pipefd[0]);  // 关闭读端
    } else {  // 父进程
        close(pipefd[0]);  // 关闭读端

        const char* msg = "Hello from parent process!";
        // 向管道写入数据
        write(pipefd[1], msg, strlen(msg));

        close(pipefd[1]);  // 关闭写端
        
        // 等待子进程结束
        wait(NULL);
    }
    return 0;
}


int main() {
    int pipefd[2];  // pipefd[0] 是读端,pipefd[1] 是写端
    
    // 创建管道
    if (pipe(pipefd) == -1) {
        perror("pipe");
        return 1;
    }

    int res = func(pipefd);
    std::cout << "res: " << res << std::endl;

    int pipefd2[2];  // pipefd[0] 是读端,pipefd[1] 是写端
    // 创建管道
    if (pipe(pipefd2) == -1) {
        perror("pipe");
        return 1;
    }

    res = func(pipefd2);
    std::cout << "res: " << res << std::endl;

    return 0;
}