zoukankan      html  css  js  c++  java
  • 进程间通信:管道 专职C++ C++博客

    进程间通信:管道 - 专职C++ - C++博客

    翻开高级unix编程,仔细看了一下管道,并将书中的例子修改并实现。
    虽然很简单,确揭示了多进程编程的基础。
    用管道非常真是非常的简单。以前只是看了,没有实践!

    #include <common.h>

    #define MAXLINE 256
    int main(int argc, char * argv[])
    {
        
    int fd[2]; //管道fd
        pid_t pid; //子进程的PID
        char line[MAXLINE];

        
    if( (pipe(fd) ) < 0 ) //创建PID,其中fd[0]为读管道,fd[1]为写管道
        {
            cout
    <<"pipe error"<<endl;
            exit(
    0);
        }


        
    if( (pid = fork() )<0//创建子进程
        {
            cout
    <<"fork error"<<endl; //一般是进程过多的时候才会出错
            exit(0);
        }

        
    //执行fork后,当前进程会得到子进程的pid,而子进程得到的是0,可以通过getppid()取得父进程
        if( pid > 0 )
        
    {
            
    //父进程向管道写数据
            char buffer[MAXLINE];
            close(fd[
    0]);
            cout
    <<"input:";
            cin.getline(buffer,MAXLINE);
            write(fd[
    1],buffer,strlen(buffer));
        }

        
    else
        
    {
            
    //子进程接收数据
            close(fd[1]);
            
    int n = read(fd[0],line,MAXLINE);
            line[n] 
    = 0;
            cout
    <<"read message:"<<line<<endl;
        }


        
    return 0;
    }


  • 相关阅读:
    modf()函数
    面向对象编程五大原则
    .Net网络资源
    整理CentOS常用命令
    在RHEL5上安装oracle10gLinux
    strchr()函数
    swab函数
    Strstr()函数
    tmpnam函数
    strdup ()函数
  • 原文地址:https://www.cnblogs.com/lexus/p/2622517.html
Copyright © 2011-2022 走看看