在Linux中,有多种进程间通信(IPC)机制可供C++程序使用。以下是一些常见的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[1]); // 关闭写端
read(pipefd[0], buffer, sizeof(buffer)); // 读取消息
std::cout << "Child received: " << buffer << std::endl;
close(pipefd[0]);
} else { // 父进程
close(pipefd[0]); // 关闭读端
const char* message = "Hello from parent!";
write(pipefd[1], message, strlen(message) + 1); // 发送消息
close(pipefd[1]);
wait(NULL); // 等待子进程结束
}
return 0;
}
#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
const char* fifo = "/tmp/myfifo";
mkfifo(fifo, 0666);
int fd = open(fifo, O_WRONLY);
if (fd == -1) {
perror("open");
return 1;
}
const char* message = "Hello from named pipe!";
write(fd, message, strlen(message) + 1);
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 World");
std::cout << "String in shared memory: " << str << std::endl;
shmdt(str);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
#include <iostream>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
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);
// P操作(等待信号量)
struct sembuf sb = {0, -1, SEM_UNDO};
semop(semid, &sb, 1);
std::cout << "Semaphore value after P operation: " << semctl(semid, 0, GETVAL, arg) << std::endl;
// V操作(释放信号量)
sb.sem_op = 1;
semop(semid, &sb, 1);
semctl(semid, 0, IPC_RMID, arg);
return 0;
}
// Unix Domain Sockets 示例
#include <iostream>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
int main() {
int sockfd;
struct sockaddr_un addr;
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket");
return 1;
}
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, "/tmp/uds.sock", sizeof(addr.sun_path)-1);
unlink("/tmp/uds.sock"); // 删除已存在的套接字文件
bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
listen(sockfd, 5);
// 接受连接
int newsockfd = accept(sockfd, NULL, NULL);
if (newsockfd == -1) {
perror("accept");
return 1;
}
// 读取数据
char buffer[256];
read(newsockfd, buffer, sizeof(buffer));
std::cout << "Received message: " << buffer << std::endl;
// 关闭套接字
close(newsockfd);
close(sockfd);
return 0;
}
在使用这些IPC机制时,请确保处理好错误情况,并在进程结束时清理资源。此外,对于共享内存和信号量,还需要考虑同步问题,以避免竞态条件。