Linux系統下c++進程間通信(IPC)方法多樣,本文介紹幾種常用方法:
- 管道(Pipes): 管道是一種半雙工通信方式,常用于父子進程間的簡單數據交換。C++程序可使用pipe()系統調用創建管道,并用read()和write()函數進行讀寫。
#include <iostream> #include <unistd.h> #include <fcntl.h> int main() { int pipefd[2]; char buffer[10]; if (pipe(pipefd) == -1) { perror("pipe"); return 1; } pid_t pid = fork(); 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]); // 關閉讀端 write(pipefd[1], "Hello from parent!", 17); close(pipefd[1]); } return 0; }
- 命名管道(Named Pipes, FIFOs): 命名管道是一種特殊文件,允許無關進程間通信。mkfifo()系統調用創建命名管道,open()、read()、write()函數用于讀寫。
#include <iostream> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> int main() { const char* fifo_name = "my_fifo"; mkfifo(fifo_name, 0666); int fd = open(fifo_name, O_RDWR); if (fd == -1) { perror("open"); return 1; } const char* message = "Hello from named pipe!"; write(fd, message, strlen(message) + 1); char buffer[100]; read(fd, buffer, sizeof(buffer)); std::cout << "Received: " << buffer << std::endl; close(fd); unlink(fifo_name); // 刪除命名管道 return 0; }
#include <iostream> #include <csignal> #include <unistd.h> void signal_handler(int signum) { std::cout << "Received signal " << signum << std::endl; } int main() { signal(SIGUSR1, signal_handler); pid_t pid = fork(); if (pid == 0) { // 子進程 sleep(2); kill(getppid(), SIGUSR1); } else { // 父進程 sleep(5); } return 0; }
- 消息隊列(Message Queues): 消息隊列允許進程發送和接收消息。msgget()、msgsnd()、msgrcv()函數用于操作消息隊列。
#include <iostream> #include <sys/msg.h> #include <sys/ipc.h> #include <cstring> // ... (消息隊列結構體和代碼,與原文類似) ...
- 共享內存(Shared Memory): 共享內存允許多個進程訪問同一內存區域。shmget()、shmat()、shmdt()函數用于操作共享內存。
#include <iostream> #include <sys/shm.h> #include <sys/ipc.h> #include <cstring> // ... (共享內存代碼,與原文類似) ...
- 信號量(Semaphores): 信號量用于進程同步和互斥。semget()、semop()、semctl()函數用于操作信號量。
#include <iostream> #include <sys/sem.h> #include <sys/ipc.h> #include <unistd.h> // ... (信號量代碼,與原文類似) ...
以上僅為部分Linux下C++進程間通信方法,選擇何種方法取決于具體應用場景。