在Linux环境下,C++程序可以使用多种进程间通信(IPC)机制。以下是一些常用的IPC方法:
管道(Pipes):
消息队列(Message Queues):
共享内存(Shared Memory):
信号(Signals):
信号量(Semaphores):
套接字(Sockets):
下面是一些简单的示例代码,展示了如何在C++中使用这些IPC机制:
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
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 <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
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 <sys/ipc.h>
#include <sys/shm.h>
#include <iostream>
#include <cstring>
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 <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <cstring>
#include <sys/mman.h>
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机制时,需要注意同步和互斥的问题,以避免竞态条件和数据不一致的问题。此外,还需要处理错误情况,确保程序的健壮性。