linux

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

小樊
37
2025-02-20 05:50:02
栏目: 编程语言

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

  1. 管道(Pipes):管道是一种半双工的通信方式,通常用于父子进程之间的通信。在C++中,可以使用pipe()系统调用创建一个管道,然后使用read()write()函数进行读写操作。
#include <iostream>
#include <unistd.h>
#include <fcntl.h>

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

    if (pipe(pipefd) == -1) {
        perror("pipe");
        return 1;
    }

    pid_t pid = fork();
    if (pid == 0) { // 子进程
        close(pipefd[1]); // 关闭写端
        read(pipefd[0], buffer, sizeof(buffer));
        std::cout << "子进程收到消息: " << 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 0;
}
  1. 命名管道(Named Pipes,FIFOs):命名管道是一种特殊类型的文件,可以在不相关的进程之间进行通信。在C++中,可以使用mkfifo()系统调用创建一个命名管道,然后使用open()read()write()函数进行读写操作。
#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

int main() {
    const char* fifo_name = "my_fifo";
    mkfifo(fifo_name, 0666);

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

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

    char buffer[10];
    read(fd, buffer, sizeof(buffer));
    std::cout << "收到消息: " << buffer << std::endl;

    close(fd);
    unlink(fifo_name);

    return 0;
}
  1. 信号(Signals):信号是一种用于进程间异步通信的机制。在C++中,可以使用signal()函数设置信号处理函数,然后使用kill()函数发送信号。
#include <iostream>
#include <csignal>
#include <unistd.h>

void signal_handler(int signum) {
    std::cout << "收到信号: " << signum << std::endl;
}

int main() {
    signal(SIGUSR1, signal_handler);

    pid_t pid = fork();
    if (pid == 0) { // 子进程
        sleep(2);
        kill(getppid(), SIGUSR1);
    } else { // 父进程
        sleep(5);
    }

    return 0;
}
  1. 消息队列(Message Queues):消息队列是一种允许进程发送和接收消息的数据结构。在C++中,可以使用msgget()msgsnd()msgrcv()函数进行操作。
#include <iostream>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <cstring>

struct msg_buffer {
    long msg_type;
    char msg_text[100];
};

int main() {
    key_t key = ftok("msgqueue_example", 'A');
    int msgid = msgget(key, 0666 | IPC_CREAT);

    msg_buffer message;
    message.msg_type = 1;
    strcpy(message.msg_text, "Hello from message queue!");

    msgsnd(msgid, &message, sizeof(message.msg_text), 0);

    msgrcv(msgid, &message, sizeof(message.msg_text), 1, 0);
    std::cout << "收到消息: " << message.msg_text << std::endl;

    msgctl(msgid, IPC_RMID, NULL);

    return 0;
}
  1. 共享内存(Shared Memory):共享内存是一种允许多个进程访问同一块内存区域的机制。在C++中,可以使用shmget()shmat()shmdt()函数进行操作。
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>

int main() {
    key_t key = ftok("shared_memory_example", 'A');
    int shmid = shmget(key, 1024, 0666 | IPC_CREAT);

    char* shared_memory = (char*)shmat(shmid, NULL, 0);
    if (shared_memory == (char*)-1) {
        perror("shmat");
        return 1;
    }

    strcpy(shared_memory, "Hello from shared memory!");

    std::cout << "共享内存中的消息: " << shared_memory << std::endl;

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

    return 0;
}
  1. 信号量(Semaphores):信号量是一种用于进程同步和互斥的机制。在C++中,可以使用semget()semop()semctl()函数进行操作。
#include <iostream>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <unistd.h>

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

int main() {
    key_t key = ftok("semaphore_example", 'A');
    int semid = semget(key, 1, 0666 | IPC_CREAT);

    union semun arg;
    arg.val = 1;
    semctl(semid, 0, SETVAL, arg);

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

    std::cout << "临界区" << std::endl;

    sb.sem_op = 1; // V操作
    semop(semid, &sb, 1);

    semctl(semid, 0, IPC_RMID, arg);

    return 0;
}

这些只是Linux中C++进程间通信的一部分方法。在实际应用中,可以根据需求选择合适的IPC机制。

0
看了该问题的人还看了