加入收藏 | 设为首页 | 会员中心 | 我要投稿 济南站长网 (https://www.0531zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

应用管道达成父子进程之间的通信

发布时间:2021-11-25 20:13:58 所属栏目:教程 来源:互联网
导读:最近在学习Linux/Unix的IPC,而通过管道是其中的一种方式。管道的限制在与,它只能实现父子进程间的通信,通常我们通常会创建一个管道,然后fork出一个子进程,在父进程关掉读端(fd[0]),在子进程里关掉写端(fd[1]),然后在父进程的写端(fd[1])写入数据

最近在学习Linux/Unix的IPC,而通过管道是其中的一种方式。管道的限制在与,它只能实现父子进程间的通信,通常我们通常会创建一个管道,然后fork出一个子进程,在父进程关掉读端(fd[0]),在子进程里关掉写端(fd[1]),然后在父进程的写端(fd[1])写入数据,在子进程中的读端(fd[0])读数据,这样就实现了父子进程间的通信。
 
实现代码如下:
 
#include <iostream>   
#include "apue.h"   
#include "err_msg.h"   
using namespace std;  
  
void print(const char * str)  
{  
    int pid = getpid();  
    cout << str << endl;  
    cout << "pid = " << pid << endl;  
}  
  
int main()  
{  
    int     n;  
    int     fd[2];  
    pid_t   pid;  
    char    line[MAXLINE];  
    cout << "MAXLINE = " << MAXLINE << endl;  
      
    if (pipe(fd) < 0)  
    {  
        err_sys("pipe error");  
    }  
      
    if ((pid = fork()) < 0)  
    {  
        err_sys("fork error");  
    }  
    else if (pid > 0)   /*parent process*/  
    {  
        close(fd[0]);  
        while (1)   
        {  
            cout << "--------------------------------" << endl;  
            print((char *)"parent process");  
            cout << "write the data to pipe" << endl;  
            write(fd[1], "hello worldn", 12);  
            cout << "--------------------------------" << endl;  
            sleep(10);  
        }  
          
    }  
    else                /*child process*/  
    {  
        close(fd[1]);  
        while (1)   
        {  
            print((char *)"child process");  
            cout << "read the data from pipe" << endl;  
            n = read(fd[0], line, MAXLINE);  
            write(STDOUT_FILENO, line, n);  
            sleep(15);  
        }  
    }  
    return 0;  
}  
 

(编辑:济南站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读