发布于2026-07-02 阅读(0)
扫一扫,手机访问
在Linux环境下,C++程序要实现多进程之间的数据交换与协同工作,进程间通信(IPC)是绕不开的核心话题。下面梳理了几种最常用的IPC方式,从经典管道到现代共享内存,几乎覆盖了实际开发中的常见场景。

接下来通过几个具体例子,看看这些机制在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;
}
#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;
}
#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;
}
#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时,同步与互斥是不可忽视的细节,否则很容易出现竞态条件或数据不一致。同时,每个系统调用都可能失败,做好错误处理,程序才能跑得稳。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8