在Linux环境下,C++程序要实现多进程之间的数据交换与协同工作,进程间通信(IPC)是绕不开的核心话题。下面梳理了几种最常用的IPC方式,从经典管道到现代共享内存,几乎覆盖了实际开发中的常见场景。

Linux C++如何进行进程间通信

接下来通过几个具体例子,看看这些机制在C++中如何落地。

匿名管道

#include 
#include 
#include 
#include 

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

    // 创建管道
    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    // 创建子进程
    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid > 0) { // 父进程
        close(pipefd[0]); // 关闭读端
        write(pipefd[1], "Hello from parent!", 20);
        close(pipefd[1]); // 关闭写端
        wait(NULL); // 等待子进程结束
    } else { // 子进程
        close(pipefd[1]); // 关闭写端
        read(pipefd[0], buffer, sizeof(buffer));
        std::cout << "Child received: " << buffer << std::endl;
        close(pipefd[0]); // 关闭读端
    }

    return 0;
}

命名管道(FIFO)

#include 
#include 
#include 
#include 

int main() {
    const char* fifo = "/tmp/myfifo";
    mkfifo(fifo, 0666);

    int fd = open(fifo, O_WRONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    write(fd, "Hello from FIFO!", 20);
    close(fd);

    fd = open(fifo, O_RDONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    char buffer[10];
    read(fd, buffer, sizeof(buffer));
    std::cout << "Read from FIFO: " << buffer << std::endl;
    close(fd);

    unlink(fifo); // 删除FIFO
    return 0;
}

共享内存(System V)

#include 
#include 
#include 
#include 

int main() {
    key_t key = ftok("shmfile", 65);
    int shmid = shmget(key, 1024, 0666|IPC_CREAT);
    char *str = (char*) shmat(shmid, (void*)0, 0);
    strcpy(str, "Hello shared memory!");
    std::cout << "Shared memory: " << str << std::endl;
    shmdt(str);
    shmctl(shmid, IPC_RMID, NULL);
    return 0;
}

POSIX共享内存

#include 
#include 
#include 
#include 
#include 
#include 

int main() {
    const char* name = "/my_shm";
    int shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
    ftruncate(shm_fd, sizeof(char) * 20);
    char* ptr = (char*) mmap(NULL, sizeof(char) * 20, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    strcpy(ptr, "Hello POSIX shared memory!");
    std::cout << "POSIX shared memory: " << ptr << std::endl;
    munmap(ptr, sizeof(char) * 20);
    shm_unlink(name);
    return 0;
}

最后提醒一句:使用IPC时,同步与互斥是不可忽视的细节,否则很容易出现竞态条件或数据不一致。同时,每个系统调用都可能失败,做好错误处理,程序才能跑得稳。

本文转载于:https://www.yisu.com/ask/81964760.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。