发布于2026-07-17 阅读(0)
扫一扫,手机访问
在Linux环境下,用C++实现多进程通信(IPC),其实可选的方案比想象中要多不少。从最经典的管道,到速度最快的共享内存,再到适用于网络通信的套接字——每种机制都有自己的适用场景和取舍。下面就来逐一梳理,并附上简单的代码示例,方便大家快速上手。

下面是一些简单的示例代码,展示如何在C++中使用这些常见的IPC机制:
#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_RDWR);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
const char* message = "Hello from FIFO!";
write(fd, message, strlen(message) + 1);
char buffer[10];
read(fd, buffer, sizeof(buffer));
std::cout << "Received: " << 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 from shared memory!");
std::cout << "Shared memory: " << str << std::endl;
shmdt(str);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
#include
#include
#include
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
};
int main() {
key_t key = ftok("semfile", 65);
int semid = semget(key, 1, 0666|IPC_CREAT);
union semun arg;
arg.val = 1; // 初始化信号量为1
semctl(semid, 0, SETVAL, arg);
// 使用semop进行P操作(等待)
struct sembuf sb = {0, -1, SEM_UNDO};
semop(semid, &sb, 1);
std::cout << "Semaphore P operation completed." << std::endl;
// 使用semop进行V操作(释放)
sb.sem_op = 1;
semop(semid, &sb, 1);
semctl(semid, 0, IPC_RMID);
return 0;
}
在使用这些IPC机制时,有几个地方需要特别留意。比如,同步问题首当其冲——无论是共享内存还是管道,不加锁或信号量的话,竞态条件随时可能冒出来。另外,错误处理和资源清理也不能马虎,尤其要注意关闭文件描述符、释放共享内存段、删除命名管道和信号量等。把这些基本功做到位,程序才能跑得又稳又快。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8