Skip to content

Instantly share code, notes, and snippets.

@pengdu
Created August 9, 2023 10:47
Show Gist options
  • Save pengdu/8612f7a03539fc8fa168622f8d964e9a to your computer and use it in GitHub Desktop.
Save pengdu/8612f7a03539fc8fa168622f8d964e9a to your computer and use it in GitHub Desktop.
chatgpt实现一个 Master-Slave 多进程架构

要实现一个 Master-Slave 多进程架构,可以使用 C++ 的进程创建和进程间通信机制,如管道、共享内存等。下面是一个简单的示例:

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

const int BUFFER_SIZE = 256;

int main() {
    int pipefd[2];
    pid_t pid;

    // 创建管道
    if (pipe(pipefd) == -1) {
        std::cerr << "Failed to create pipe" << std::endl;
        return 1;
    }

    // 创建子进程
    pid = fork();
    if (pid == -1) {
        std::cerr << "Failed to create child process" << std::endl;
        return 1;
    }

    if (pid == 0) {
        // 子进程为 Slave
        close(pipefd[0]);  // 关闭读端

        // 执行 Slave 逻辑
        std::cout << "Slave: I'm ready!" << std::endl;

        // 通知 Master 可以开始工作
        const char* message = "Slave is ready";
        write(pipefd[1], message, strlen(message) + 1);

        close(pipefd[1]);  // 关闭写端
        return 0;
    } else {
        // 父进程为 Master
        close(pipefd[1]);  // 关闭写端

        // 等待 Slave 准备就绪
        char buffer[BUFFER_SIZE];
        read(pipefd[0], buffer, BUFFER_SIZE);
        std::cout << "Master: I'm ready!" << std::endl;

        // 执行 Master 逻辑

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

在这个示例中,我们使用 pipe 函数创建了一个管道,用于实现进程间的通信。然后,使用 fork 函数创建了一个子进程。

在子进程中,即 Slave 进程中,我们关闭了管道的读端,执行了 Slave 的逻辑,并向管道的写端写入了一条消息,表示 Slave 已经准备就绪。

在父进程中,即 Master 进程中,我们关闭了管道的写端,然后使用 read 函数从管道的读端读取了 Slave 发送的消息,表示 Slave 已经准备就绪。

接下来,Master 进程可以执行自己的逻辑。

最后,我们关闭了管道的读端,使用 wait 函数等待子进程结束。

需要注意的是,这只是一个简单的示例,实际的 Master-Slave 多进程架构可能涉及更复杂的进程间通信和任务分配机制,具体实现方式会根据具体需求而有所不同。

希望对你有帮助!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment