Linux系统下C++进程间通信(IPC)方法多样,本文介绍几种常用方法:
#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; }
#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; }
#include <iostream> #include <sys/msg.h> #include <sys/ipc.h> #include <cstring> // ... (消息队列结构体和代码,与原文类似) ...
#include <iostream> #include <sys/shm.h> #include <sys/ipc.h> #include <cstring> // ... (共享内存代码,与原文类似) ...
#include <iostream> #include <sys/sem.h> #include <sys/ipc.h> #include <unistd.h> // ... (信号量代码,与原文类似) ...
以上仅为部分Linux下C++进程间通信方法,选择何种方法取决于具体应用场景。
以上就是C++如何在Linux中进行进程间通信的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号