linux

C++在Linux中的进程间通信

小樊
48
2025-06-27 22:59:29
栏目: 编程语言

在Linux中,C++程序可以使用多种进程间通信(IPC)机制来在不同的进程之间传递数据和信息。以下是一些常见的IPC方法:

  1. 管道(Pipes):

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

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

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

    • 允许多个进程访问同一块物理内存区域,是最快的IPC形式之一。
  5. 信号量(Semaphores):

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

    • 通常用于网络通信,但也可以用于同一台机器上的进程间通信。

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

匿名管道

#include <unistd.h>
#include <iostream>

int main() {
    int pipefd[2];
    char buffer[256];

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

    // 父进程关闭写端,子进程关闭读端
    if (fork() == 0) {
        close(pipefd[1]); // 子进程关闭写端
        read(pipefd[0], buffer, sizeof(buffer)); // 子进程读数据
        std::cout << "Child received: " << buffer << std::endl;
        close(pipefd[0]);
    } else {
        close(pipefd[0]); // 父进程关闭读端
        const char* message = "Hello from parent!";
        write(pipefd[1], message, strlen(message) + 1); // 父进程写数据
        close(pipefd[1]);
    }

    return EXIT_SUCCESS;
}

命名管道(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 EXIT_FAILURE;
    }

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

    char buffer[256];
    read(fd, buffer, sizeof(buffer));
    std::cout << "Received: " << buffer << std::endl;

    close(fd);
    unlink(fifo);

    return EXIT_SUCCESS;
}

共享内存

#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 world");
    std::cout << "String in memory: " << str << std::endl;

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

    return 0;
}

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

0
看了该问题的人还看了