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++进程间通信方法,选择何种方法取决于具体应用场景。