在Linux环境下,C++可以通过多种方式实现进程间通信(IPC)。以下是一些常见的IPC机制:
管道(Pipes):
信号(Signals):
消息队列(Message Queues):
共享内存(Shared Memory):
信号量(Semaphores):
套接字(Sockets):
下面是一些简单的示例代码,展示了如何在C++中使用这些IPC机制:
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
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]); // 关闭读端
const char* message = "Hello from parent!";
write(pipefd[1], message, strlen(message) + 1); // 写入数据
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 <iostream>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
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);
return 0;
}
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
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;
}
请注意,这些示例仅用于演示目的,实际应用中可能需要更复杂的错误处理和同步机制。在使用共享内存时,通常需要结合信号量来避免竞态条件。在使用套接字进行IPC时,可以使用UNIX域套接字,它提供了类似于TCP/IP套接字的接口,但是用于本地进程间通信。