登录
首页 >  文章 >  linux

Linux下C++进程间通信详解

时间:2025-03-02 20:18:18 412浏览 收藏

本文介绍了Linux系统下C++进程间通信(IPC)的几种常用方法,包括管道(Pipes)、命名管道(Named Pipes)、信号(Signals)、消息队列(Message Queues)、共享内存(Shared Memory)和信号量(Semaphores)。 文章通过代码示例详细讲解了每种方法的实现细节,例如使用`pipe()`、`mkfifo()`、`signal()`、`msgget()`、`shmget()`和`semget()`等系统调用完成进程间数据交换和同步。选择合适的IPC方法取决于具体的应用场景和需求,本文旨在为C++开发者在Linux环境下进行进程间通信提供参考。

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

Linux系统下C++进程间通信(IPC)方法多样,本文介绍几种常用方法:

  1. 管道(Pipes): 管道是一种半双工通信方式,常用于父子进程间的简单数据交换。C++程序可使用pipe()系统调用创建管道,并用read()write()函数进行读写。
#include 
#include 
#include 

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 << "Child received: " << buffer << std::endl;
        close(pipefd[0]);
    } else { // 父进程
        close(pipefd[0]); // 关闭读端
        write(pipefd[1], "Hello from parent!", 17);
        close(pipefd[1]);
    }

    return 0;
}
  1. 命名管道(Named Pipes, FIFOs): 命名管道是一种特殊文件,允许无关进程间通信。mkfifo()系统调用创建命名管道,open()read()write()函数用于读写。
#include 
#include 
#include 
#include 

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[100];
    read(fd, buffer, sizeof(buffer));
    std::cout << "Received: " << buffer << std::endl;
    close(fd);
    unlink(fifo_name); // 删除命名管道

    return 0;
}
  1. 信号(Signals): 信号用于进程间异步通信。signal()函数设置信号处理函数,kill()函数发送信号。
#include 
#include 
#include 

void signal_handler(int signum) {
    std::cout << "Received signal " << 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): 消息队列允许进程发送和接收消息。msgget()msgsnd()msgrcv()函数用于操作消息队列。
#include 
#include 
#include 
#include 

// ... (消息队列结构体和代码,与原文类似) ...
  1. 共享内存(Shared Memory): 共享内存允许多个进程访问同一内存区域。shmget()shmat()shmdt()函数用于操作共享内存。
#include 
#include 
#include 
#include 

// ... (共享内存代码,与原文类似) ...
  1. 信号量(Semaphores): 信号量用于进程同步和互斥。semget()semop()semctl()函数用于操作信号量。
#include 
#include 
#include 
#include 

// ... (信号量代码,与原文类似) ...

以上仅为部分Linux下C++进程间通信方法,选择何种方法取决于具体应用场景。

本篇关于《Linux下C++进程间通信详解》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>