温馨提示×

C++在Linux下如何实现进程间通信

小樊
38
2025-02-22 06:24:25
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Linux下,C++可以通过多种方式实现进程间通信(IPC),以下是一些常用的IPC机制:

  1. 管道(Pipes):

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

    • 用于通知接收进程某个事件已经发生。
  3. 消息队列(Message Queues):

    • 允许进程发送和接收消息。
  4. 共享内存(Shared Memory):

    • 多个进程可以映射到同一块物理内存地址,实现高效的数据交换。
  5. 信号量(Semaphores):

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

    • 既可以用于本地进程间通信,也可以用于网络通信。

下面是一些简单的示例代码,展示了如何在Linux下使用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]); // 关闭读端
        const char* message = "Hello from parent";
        write(pipefd[1], message, strlen(message) + 1);
        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)

// 创建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_RDWR);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    const char* message = "Hello from FIFO";
    write(fd, message, strlen(message) + 1);

    char buffer[10];
    read(fd, buffer, sizeof(buffer));
    std::cout << "Received: " << 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);

    if (str == (char*)(-1)) {
        perror("shmat");
        exit(EXIT_FAILURE);
    }

    strcpy(str, "Hello shared memory");
    std::cout << "Shared memory: " << str << std::endl;

    shmdt(str);
    shmctl(shmid, IPC_RMID, NULL);

    return 0;
}

信号量

// 使用System V信号量
#include <sys/ipc.h>
#include <sys/sem.h>
#include <iostream>

union semun {
    int val;
    struct semid_ds *buf;
    unsigned short *array;
};

int main() {
    key_t key = ftok("semfile", 65);
    int semid = semget(key, 1, 0666|IPC_CREAT);

    union semun arg;
    arg.val = 1; // 初始化信号量为1
    semctl(semid, 0, SETVAL, arg);

    // P操作(等待信号量)
    struct sembuf sb = {0, -1, SEM_UNDO};
    semop(semid, &sb, 1);

    std::cout << "Semaphore value decreased to " << arg.val << std::endl;

    // V操作(释放信号量)
    arg.val = 1;
    sb.sem_op = 1;
    semop(semid, &sb, 1);

    semctl(semid, 0, IPC_RMID, arg);

    return 0;
}

套接字

// 使用Unix Domain Sockets
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <iostream>
#include <cstring>

int main() {
    const char* socket_path = "/tmp/uds.sock";
    int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (sockfd == -1) {
        perror("socket");
        return 1;
    }

    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path)-1);

    if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        perror("bind");
        close(sockfd);
        return 1;
    }

    if (listen(sockfd, 5) == -1) {
        perror("listen");
        close(sockfd);
        return 1;
    }

    int clientfd = accept(sockfd, NULL, NULL);
    if (clientfd == -1) {
        perror("accept");
        close(sockfd);
        return 1;
    }

    char buffer[10];
    read(clientfd, buffer, sizeof(buffer));
    std::cout << "Server received: " << buffer << std::endl;

    const char* message = "Hello from server";
    write(clientfd, message, strlen(message) + 1);

    close(clientfd);
    close(sockfd);

    return 0;
}

在使用这些IPC机制时,需要注意同步和互斥的问题,以避免竞态条件和数据不一致。此外,还需要处理错误情况,确保程序的健壮性。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:C++在Linux上如何进行进程间通信

0