溫馨提示×

Linux下C++如何實現進程間通信

小樊
49
2025-04-04 01:38:30
欄目: 編程語言

在Linux下,C++可以通過多種方式實現進程間通信(IPC),以下是一些常見的IPC機制:

  1. 管道(Pipes):

    • 匿名管道(Anonymous Pipes):通常用于父子進程之間的通信。
    • 命名管道(Named Pipes,FIFOs):允許無親緣關系的進程之間進行通信。
  2. 信號(Signals):

    • 用于通知接收進程某個事件已經發生。
  3. 消息隊列(Message Queues):

    • 允許進程發送和接收消息數據塊。
  4. 共享內存(Shared Memory):

    • 多個進程可以映射同一段物理內存,實現高效的數據交換。
  5. 信號量(Semaphores):

    • 用于進程同步,控制多個進程對共享資源的訪問。
  6. 套接字(Sockets):

    • 支持不同機器間的進程通信,也可以用于同一臺機器上的進程通信。

下面是一些簡單的示例代碼,展示了如何在C++中使用這些IPC機制:

  1. 匿名管道(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[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;
}
  1. 命名管道(Named Pipes,FIFOs)示例:

首先創建一個命名管道:

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_WRONLY);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }
    const char* message = "Hello from FIFO!";
    write(fd, message, strlen(message) + 1);
    close(fd);
    return 0;
}

// 讀取進程
#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

int main() {
    const char* fifo = "myfifo";
    int fd = open(fifo, O_RDONLY);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }
    char buffer[10];
    read(fd, buffer, sizeof(buffer));
    std::cout << "Received: " << buffer << std::endl;
    close(fd);
    return 0;
}
  1. 共享內存示例:
#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;
}

這些示例僅用于演示如何在C++中使用Linux IPC機制。在實際應用中,可能需要更復雜的錯誤處理和同步機制。此外,還有其他IPC方法,如信號量、消息隊列和套接字,可以根據具體需求選擇合適的IPC機制。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女