Welcome 微信登录

首页 / 操作系统 / Linux / 应用管道实现父子进程之间的通信

最近在学习Linux/Unix的IPC,而通过管道是其中的一种方式。管道的限制在与,它只能实现父子进程间的通信,通常我们通常会创建一个管道,然后fork出一个子进程,在父进程关掉读端(fd[0]),在子进程里关掉写端(fd[1]),然后在父进程的写端(fd[1])写入数据,在子进程中的读端(fd[0])读数据,这样就实现了父子进程间的通信。实现代码如下:
  1. #include <iostream>   
  2. #include "apue.h"   
  3. #include "err_msg.h"   
  4. using namespace std;  
  5.   
  6. void print(const char * str)  
  7. {  
  8.     int pid = getpid();  
  9.     cout << str << endl;  
  10.     cout << "pid = " << pid << endl;  
  11. }  
  12.   
  13. int main()  
  14. {  
  15.     int     n;  
  16.     int     fd[2];  
  17.     pid_t   pid;  
  18.     char    line[MAXLINE];  
  19.     cout << "MAXLINE = " << MAXLINE << endl;  
  20.       
  21.     if (pipe(fd) < 0)  
  22.     {  
  23.         err_sys("pipe error");  
  24.     }  
  25.       
  26.     if ((pid = fork()) < 0)  
  27.     {  
  28.         err_sys("fork error");  
  29.     }  
  30.     else if (pid > 0)   /*parent process*/  
  31.     {  
  32.         close(fd[0]);  
  33.         while (1)   
  34.         {  
  35.             cout << "--------------------------------" << endl;  
  36.             print((char *)"parent process");  
  37.             cout << "write the data to pipe" << endl;  
  38.             write(fd[1], "hello world ", 12);  
  39.             cout << "--------------------------------" << endl;  
  40.             sleep(10);  
  41.         }  
  42.           
  43.     }  
  44.     else                /*child process*/  
  45.     {  
  46.         close(fd[1]);  
  47.         while (1)   
  48.         {  
  49.             print((char *)"child process");  
  50.             cout << "read the data from pipe" << endl;  
  51.             n = read(fd[0], line, MAXLINE);  
  52.             write(STDOUT_FILENO, line, n);  
  53.             sleep(15);  
  54.         }  
  55.     }  
  56.     return 0;  
  57. }