c语言+pipe实现父子进程通信(双向通信+发送多条信息)

发布于:2024-03-27 ⋅ 阅读:(78) ⋅ 点赞:(0)

chatgpt写的,我调了一下,觉得挺好,发个博客记录一下
测试环境是ubuntu
感觉关键就是write的时候要sleep,然后写的时候要while读。总觉得怪怪的,干脆一次读写完算了。

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

#define BUFFER_SIZE 256

int main() {
    int pipe_parent_child[2];  // 父进程到子进程的管道
    int pipe_child_parent[2];  // 子进程到父进程的管道
    pid_t pid;
    char buffer[BUFFER_SIZE];

    // 创建父子进程间的管道
    if (pipe(pipe_parent_child) == -1 || pipe(pipe_child_parent) == -1) {
        perror("Pipe creation failed");
        exit(EXIT_FAILURE);
    }

    // 创建子进程
    pid = fork();

    if (pid == -1) {
        perror("Fork failed");
        exit(EXIT_FAILURE);
    }

    if (pid > 0) { // Parent process
        close(pipe_parent_child[0]); // 父进程关闭从父进程到子进程的读端
        close(pipe_child_parent[1]); // 父进程关闭从子进程到父进程的写端

        // 父进程向子进程发送消息
        const char* messages_to_child[] = {"Hello, child!", "How are you?", "Do you want to play?"};
        for (int i = 0; i < sizeof(messages_to_child) / sizeof(messages_to_child[0]); ++i) {
            write(pipe_parent_child[1], messages_to_child[i], strlen(messages_to_child[i]) + 1);
            printf("Parent sent: %s\n", messages_to_child[i]);
            sleep(1); // 延迟一秒,模拟发送多条消息的间隔
        }

        close(pipe_parent_child[1]); // 关闭父进程到子进程的写端,表示发送完毕

        // 父进程从子进程接收消息
        while (read(pipe_child_parent[0], buffer, BUFFER_SIZE) > 0) {
            printf("Parent received: %s\n", buffer);
        }

        close(pipe_child_parent[0]); // 关闭从子进程到父进程的读端
    } else { // Child process
        close(pipe_parent_child[1]); // 子进程关闭从父进程到子进程的写端
        close(pipe_child_parent[0]); // 子进程关闭从子进程到父进程的读端

        // 子进程从父进程接收消息
        while (read(pipe_parent_child[0], buffer, BUFFER_SIZE) > 0) {
            printf("Child received: %s\n", buffer);
        }
        close(pipe_parent_child[0]); // 关闭从父进程到子进程的读端
        // 子进程向父进程发送消息
        const char* messages_to_parent[] = {"Hi, parent!", "I'm fine, thanks.", "Sure!"};
        for (int i = 0; i < sizeof(messages_to_parent) / sizeof(messages_to_parent[0]); ++i) {
            write(pipe_child_parent[1], messages_to_parent[i], strlen(messages_to_parent[i]) + 1);
            printf("Child sent: %s\n", messages_to_parent[i]);
            sleep(1); // 延迟一秒,模拟发送多条消息的间隔
        }
        close(pipe_child_parent[1]); // 关闭从子进程到父进程的写端,表示发送完毕
    }

    return 0;
}

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到