在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时,同步与互斥是不可忽视的细节,否则很容易出现竞态条件或数据不一致。同时,每个系统调用都可能失败,做好错误处理,程序才能跑得稳。