温馨提示×

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

小樊
47
2025-11-11 09:43:18
栏目: 编程语言

在Linux环境下,C++程序可以使用多种进程间通信(IPC)机制。以下是一些常用的IPC方法:

  1. 管道(Pipes):

    • 匿名管道(Anonymous Pipes): 通常用于父子进程之间的通信。
    • 命名管道(Named Pipes, FIFOs): 允许无亲缘关系的进程之间进行通信。
  2. 消息队列(Message Queues):

    • System V消息队列
    • POSIX消息队列
  3. 共享内存(Shared Memory):

    • System V共享内存
    • POSIX共享内存
  4. 信号(Signals):

    • 用于进程间的异步通知。
  5. 信号量(Semaphores):

    • 用于进程同步,控制对共享资源的访问。
  6. 套接字(Sockets):

    • 既可以用于本地进程间通信(如Unix Domain Sockets),也可以用于网络通信。

下面是一些简单的示例代码,展示了如何在C++中使用这些IPC机制:

匿名管道

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

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 <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>

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 <sys/ipc.h>
#include <sys/shm.h>
#include <iostream>
#include <cstring>

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 <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <cstring>
#include <sys/mman.h>

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机制时,需要注意同步和互斥的问题,以避免竞态条件和数据不一致的问题。此外,还需要处理错误情况,确保程序的健壮性。

0