进程间通信

进程通信的目的

  • 数据传输:一个进程需要将它的数据发送给另一个进程
  • 资源共享:多个进程之间共享同样的资源。
  • 通知事件:一个进程需要向另一个或一组进程发送消息,通知它(它们)发生了某种事件(如进程终止 时要通知父进程)。
  • 进程控制:有些进程希望完全控制另一个进程的执行(如Debug进程),此时控制进程希望能够拦截另 一个进程的所有陷入和异常,并能够及时知道它的状态改变。

 

进程是独立的,但不是彻底独立,进程间依旧可以共享、传输数据,但进程通信间花费的成本较大

 

匿名通道

就是实现通信的

 

 父进程传数据到文件缓冲区,子进程从文件缓冲区取数据,也是一种通信

 

pipe即是系统提供完成以上操作的

返回一个数组,下标为0的代表读数据,1代表写数据,返回0代表成功,非0代表失败

pipe内部,自带访问控制机制,同步和互斥机制

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <unordered_map>
#include <ctime>
#include <cstdlib>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <cassert>
using namespace std;

int main()
{

    //1.创建管道
    int pipefd[2]={0};
    if(pipe(pipefd)!=0)//如果创建失败
    {
        cerr<<"pipe error"<<endl;
        return 1;
    }
    //2.创建子进程
    pid_t id=fork();
    if(id<0)//如果创建失败
    {
        cerr<<"fork error"<<endl;
        return 2;
    }
    else if(id==0)//当是子进程时
    {
        #define NUM 1024
        char buffer[NUM];
        //子进程用来进程读取 那么就关掉它的写
        close(pipefd[1]);
        while(1)
        {
            memset(buffer,0,sizeof(buffer));//把数组内全部修改为0
            ssize_t s=read(pipefd[0],buffer,sizeof(buffer)-1);//从pipefd 0下标读到buffer内 \0不用读
            if(s>0)
            {
                //读取成功
                buffer[s]='\0';
                cout<<"子进程收到信息,内容是:\n"<<buffer;
            }
            else if(s==0)
            {
                cout<<"父进程写完了,我也退出了"<<endl;
                break;
            }
            else
            {
                //位置错误
            }
        }
        close(pipefd[0]);//当都读完时,就关闭读
        exit(0);
    }
    else
    {
        //父进程用来写 就要关掉读
        close(pipefd[0]);
        const char *msg="你好子进程,我是父进程.\n";
        int cnt=0;
        while(cnt<5)
        {
            write(pipefd[1],msg,strlen(msg));
            cnt++;
        }
        //写完就关闭写
        close(pipefd[1]);
        cout<<"父进程写完了"<<endl;
    }
    pid_t res=waitpid(id,nullptr,0);
    if(res>0)
    {
        cout<<"等待子进程成功"<<endl;
    }
    return 0;
}

 

posted @ 2022-11-04 23:09  lemon-Breeze  阅读(28)  评论(0编辑  收藏  举报