亚洲国产第一_开心网五月色综合亚洲_日本一级特黄特色大片免费观看_久久久久久久久久免观看

Hello! 歡迎來到小浪云!


C++如何在Linux中進行進程間通信


avatar
小浪云 2025-02-20 100

C++如何在Linux中進行進程間通信

Linux系統(tǒng)下c++進程間通信(IPC)方法多樣,本文介紹幾種常用方法:

  1. 管道(Pipes): 管道是一種半雙工通信方式,常用于父子進程間的簡單數(shù)據(jù)交換。C++程序可使用pipe()系統(tǒng)調(diào)用創(chuàng)建管道,并用read()和write()函數(shù)進行讀寫。
#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]); // 關(guān)閉寫端         read(pipefd[0], buffer, sizeof(buffer));         std::cout << "Child received: " << buffer << std::endl;         close(pipefd[0]);     } else { // 父進程         close(pipefd[0]); // 關(guān)閉讀端         write(pipefd[1], "Hello from parent!", 17);         close(pipefd[1]);     }      return 0; }
  1. 命名管道(Named Pipes, FIFOs): 命名管道是一種特殊文件,允許無關(guān)進程間通信。mkfifo()系統(tǒng)調(diào)用創(chuàng)建命名管道,open()、read()、write()函數(shù)用于讀寫。
#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; }
  1. 信號(signals): 信號用于進程間異步通信。signal()函數(shù)設(shè)置信號處理函數(shù),kill()函數(shù)發(fā)送信號。
#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; }
  1. 消息隊列(Message Queues): 消息隊列允許進程發(fā)送和接收消息。msgget()、msgsnd()、msgrcv()函數(shù)用于操作消息隊列。
#include <iostream> #include <sys/msg.h> #include <sys/ipc.h> #include <cstring>  // ... (消息隊列結(jié)構(gòu)體和代碼,與原文類似) ...
  1. 共享內(nèi)存(Shared Memory): 共享內(nèi)存允許多個進程訪問同一內(nèi)存區(qū)域。shmget()、shmat()、shmdt()函數(shù)用于操作共享內(nèi)存。
#include <iostream> #include <sys/shm.h> #include <sys/ipc.h> #include <cstring>  // ... (共享內(nèi)存代碼,與原文類似) ...
  1. 信號量(Semaphores): 信號量用于進程同步和互斥。semget()、semop()、semctl()函數(shù)用于操作信號量。
#include <iostream> #include <sys/sem.h> #include <sys/ipc.h> #include <unistd.h>  // ... (信號量代碼,與原文類似) ...

以上僅為部分Linux下C++進程間通信方法,選擇何種方法取決于具體應(yīng)用場景。

相關(guān)閱讀