手机版
你好,游客 登录 注册
背景:
阅读新闻

应用管道实现父子进程之间的通信

[日期:2011-07-31] 来源:Linux社区  作者:acb0y [字体:大 中 小]

最近在学习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\n", 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. }  
linux
相关资讯       Linux编程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款