linux

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

小樊
46
2025-03-13 00:32:22
栏目: 编程语言
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):

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

下面是一些简单的示例代码:

匿名管道示例(父子进程通信):

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

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[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;
}

命名管道示例(无亲缘关系进程通信):

首先,创建一个命名管道:

mkfifo myfifo

然后,使用C++代码进行读写操作:

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

int main() {
    const char* fifo = "myfifo";
    int fd = open(fifo, O_RDWR);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    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);
    return 0;
}

共享内存示例:

#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>

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;
}

这些示例仅用于演示目的,实际应用中可能需要更复杂的错误处理和同步机制。在选择IPC方法时,请根据您的需求和场景进行选择。

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

相关推荐:Linux系统中C++如何进行进程间通信

0
看了该问题的人还看了