在Linux环境下,C++可以通过多种方式实现多进程通信(IPC)。以下是一些常用的IPC机制:
管道(Pipes):
信号(Signals):
消息队列(Message Queues):
共享内存(Shared Memory):
信号量(Semaphores):
套接字(Sockets):
内存映射文件(Memory-mapped Files):
下面是一些简单的示例代码,展示了如何在C++中使用这些IPC机制:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.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_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 <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 from shared memory!");
std::cout << "Shared memory: " << str << std::endl;
shmdt(str);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
#include <sys/ipc.h>
#include <sys/sem.h>
#include <iostream>
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机制时,需要注意同步问题,以避免竞态条件和其他并发问题。此外,还需要考虑错误处理和资源清理,确保程序的健壮性。