在Linux系統中,C++可以通過多種方式進行進程間通信(IPC),以下是一些常見的IPC方法:
管道(Pipes):
信號(Signals):
消息隊列(Message Queues):
共享內存(Shared Memory):
信號量(Semaphores):
套接字(Sockets):
下面是一些簡單的示例代碼:
匿名管道示例(父子進程通信):
#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;
}
命名管道示例(無親緣關系進程通信):
首先,創建一個命名管道:
mkfifo myfifo
然后,使用C++代碼進行讀寫操作:
#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
const char* fifo = "myfifo";
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);
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方法時,請根據您的需求和場景進行選擇。