Linux C++如何进行进程间通信
LinuxC++进程间通信方式包括管道(匿名与命名)、消息队列、共享内存、信号、信号量及套接字。其中共享内存效率最高,管道常用于父子进程通信,信号处理异步事件,消息队列实现解耦,套接字支持网络通信。
在Linux环境下,C++程序要实现多进程之间的数据交换与协同工作,进程间通信(IPC)是绕不开的核心话题。下面梳理了几种最常用的IPC方式,从经典管道到现代共享内存,几乎覆盖了实际开发中的常见场景。

- 管道(Pipes):匿名管道用于父子进程间,命名管道(FIFO)则允许任意两个进程通信。
- 消息队列(Message Queues):包括System V和POSIX两种标准,适合结构化消息的异步传递。
- 共享内存(Shared Memory):同样分为System V和POSIX两套API,是效率最高的IPC方式。
- 信号(Signals):用于异步通知,比如进程终止或自定义事件。
- 信号量(Semaphores):用来控制对共享资源的并发访问,避免竞争条件。
- 套接字(Sockets):Unix Domain Socket专为本地通信设计,网络Socket则跨越不同机器。
接下来通过几个具体例子,看看这些机制在C++中如何落地。
匿名管道
#include
#include
#include
#include
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]); // 关闭读端
write(pipefd[1], "Hello from parent!", 20);
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;
}
命名管道(FIFO)
#include
#include
#include
#include
int main() {
const char* fifo = "/tmp/myfifo";
mkfifo(fifo, 0666);
int fd = open(fifo, O_WRONLY);
if (fd == -1) {
perror("open");
return 1;
}
write(fd, "Hello from FIFO!", 20);
close(fd);
fd = open(fifo, O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
char buffer[10];
read(fd, buffer, sizeof(buffer));
std::cout << "Read from FIFO: " << buffer << std::endl;
close(fd);
unlink(fifo); // 删除FIFO
return 0;
}
共享内存(System V)
#include
#include
#include
#include
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;
}
POSIX共享内存
#include
#include
#include
#include
#include
#include
int main() {
const char* name = "/my_shm";
int shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, sizeof(char) * 20);
char* ptr = (char*) mmap(NULL, sizeof(char) * 20, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
strcpy(ptr, "Hello POSIX shared memory!");
std::cout << "POSIX shared memory: " << ptr << std::endl;
munmap(ptr, sizeof(char) * 20);
shm_unlink(name);
return 0;
}
最后提醒一句:使用IPC时,同步与互斥是不可忽视的细节,否则很容易出现竞态条件或数据不一致。同时,每个系统调用都可能失败,做好错误处理,程序才能跑得稳。
LibreOffice桌面版提供Writer、Calc、Impress等办公组件,可本地处理文档并交换Office格式。了解实际功能、商用许可、兼容性检查和企业支持的区别。
Numbers macOS版用于预算、数据整理和可视化报告,支持公式、图表、数据透视表及iCloud协作。了解Excel文件交换、Mac安装条件和多端使用差异。
Qoder智能体工作台将编程任务、项目知识整理和自动化集中处理。本页介绍任务执行、Repo Wiki与结果审阅,区分Qoder IDE、系统安装选项和账户套餐,并提供官方下载入口。
微信Windows版适合电脑聊天、会话查找和文件传送。本页说明登录与文件管理、电脑办公优势,以及大文件失败、版本差异和本地记录的核对方法。
LibreOffice桌面版提供Writer、Calc、Impress等办公组件,可本地处理文档并交换Office格式。了解实际功能、商用许可、兼容性检查和企业支持的区别。
Qoder智能体工作台将编程任务、项目知识整理和自动化集中处理。本页介绍任务执行、Repo Wiki与结果审阅,区分Qoder IDE、系统安装选项和账户套餐,并提供官方下载入口。






