linux

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

小樊
44
2025-12-14 23:46:01
栏目: 编程语言

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

1. 管道(Pipes)

管道是一种半双工的通信方式,通常用于父子进程之间的通信。

无名管道(Anonymous Pipes)

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

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

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

    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid == 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]);
        wait(NULL); // 等待子进程结束
    }

    return 0;
}

命名管道(Named Pipes, FIFOs)

#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
    const char* fifo_name = "/tmp/myfifo";
    int fd;
    char buffer[256];

    // 创建命名管道
    if (mkfifo(fifo_name, 0666) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }

    fd = open(fifo_name, O_RDWR);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    // 写入数据
    const char* message = "Hello from FIFO";
    write(fd, message, strlen(message) + 1);

    // 读取数据
    read(fd, buffer, sizeof(buffer));
    std::cout << "Received: " << buffer << std::endl;

    close(fd);
    unlink(fifo_name); // 删除命名管道

    return 0;
}

2. 消息队列(Message Queues)

消息队列允许进程以消息的形式交换数据。

#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <cstring>

struct msg_buffer {
    long mtype;
    char mtext[100];
};

int main() {
    key_t key = ftok("msgqueue_example.c", 65);
    int msgid = msgget(key, 0666 | IPC_CREAT);

    if (msgid == -1) {
        perror("msgget");
        exit(EXIT_FAILURE);
    }

    msg_buffer buffer;
    buffer.mtype = 1;
    strcpy(buffer.mtext, "Hello from message queue");

    // 发送消息
    if (msgsnd(msgid, &buffer, sizeof(buffer.mtext), 0) == -1) {
        perror("msgsnd");
        exit(EXIT_FAILURE);
    }

    // 接收消息
    if (msgrcv(msgid, &buffer, sizeof(buffer.mtext), 1, 0) == -1) {
        perror("msgrcv");
        exit(EXIT_FAILURE);
    }

    std::cout << "Received message: " << buffer.mtext << std::endl;

    msgctl(msgid, IPC_RMID, NULL); // 删除消息队列

    return 0;
}

3. 共享内存(Shared Memory)

共享内存是最快的IPC机制之一,因为它避免了数据的复制。

#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>

int main() {
    key_t key = ftok("shm_example.c", 65);
    int shmid = shmget(key, 1024, 0666 | IPC_CREAT);

    if (shmid == -1) {
        perror("shmget");
        exit(EXIT_FAILURE);
    }

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

    strcpy(str, "Hello from shared memory");

    std::cout << "Message written in memory: " << str << std::endl;

    shmdt(str); // 分离共享内存

    // 删除共享内存
    shmctl(shmid, IPC_RMID, NULL);

    return 0;
}

4. 信号量(Semaphores)

信号量用于进程同步,防止多个进程同时访问共享资源。

#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>

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

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

    if (semid == -1) {
        perror("semget");
        exit(EXIT_FAILURE);
    }

    union semun arg;
    arg.val = 1; // 初始化信号量为1
    if (semctl(semid, 0, SETVAL, arg) == -1) {
        perror("semctl");
        exit(EXIT_FAILURE);
    }

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

    std::cout << "Semaphore P operation completed" << std::endl;

    // V操作(释放信号量)
    sb.sem_op = 1;
    if (semop(semid, &sb, 1) == -1) {
        perror("semop");
        exit(EXIT_FAILURE);
    }

    std::cout << "Semaphore V operation completed" << std::endl;

    semctl(semid, 0, IPC_RMID); // 删除信号量

    return 0;
}

5. 套接字(Sockets)

套接字是一种通用的IPC机制,不仅限于本地进程间通信,还可以用于网络通信。

Unix Domain Sockets

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>

int main() {
    struct sockaddr_un addr;
    int sockfd, connfd;
    char buffer[1024];

    sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, "/tmp/unix_socket", sizeof(addr.sun_path) - 1);

    unlink("/tmp/unix_socket"); // 删除已存在的套接字文件

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

    if (listen(sockfd, 5) == -1) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    connfd = accept(sockfd, NULL, NULL);
    if (connfd == -1) {
        perror("accept");
        exit(EXIT_FAILURE);
    }

    read(connfd, buffer, sizeof(buffer));
    std::cout << "Received: " << buffer << std::endl;

    close(connfd);
    close(sockfd);

    return 0;
}

这些是Linux下C++常用的进程间通信方法。每种方法都有其适用的场景和优缺点,选择合适的方法取决于具体的需求。

0
看了该问题的人还看了