Linux多进程编程三——进程通信


一、进程通信基础

1.什么是进程通信

  进程是一个独立的资源分配单元,不同进程(这里所说的进程通常指的是用户进程)之间的资源是独立的,没有关联,不能在一个进程中直接访问另一个进程的资源。但是,进程不是孤立的,不同的进程需要进行信息的交互和状态的传递等,因此需要进程间通信( IPC:Inter Processes Communication )。

  进程间通信的目的:

  1.数据传输:一个进程需要将它的数据发送给另一个进程

  2.通知事件:一个进程需要向另一个或一组进程发送消息,通知其发生了某件事(如子进程终止需要通知父进程)

  3.资源共享:多个进程之间共享同样的资源。

  4.进程控制:有些进程希望完全控制另一个进程的运行(如DEBUG),此时控制进程希望能够拦截另一个进程的所有陷入和异常。

2.进程间通信方式分类

二、管道通信

1.匿名管道通信

1.概念

  管道也叫无名(匿名)管道,它是是 UNIX 系统 IPC(进程间通信)的最古老形式, 所有的 UNIX 系统都支持这种通信机制。统计一个目录中文件的数目命令:ls | wc –l,为了执行该命令,shell 创建了两 个进程来分别执行 ls 和 wc。

2.(匿名)管道特点

  1.管道其实是一个在内核内存中维护的缓冲器,这个缓冲器的存储能力是有限的,不同的 操作系统大小不一定相同。

  2.管道拥有文件的特质:读操作、写操作,匿名管道没有文件实体,有名管道有文件实体, 但不存储数据。可以按照操作文件的方式对管道进行操作。

  3.一个管道是一个字节流,使用管道时不存在消息或者消息边界的概念,从管道读取数据 的进程可以读取任意大小的数据块,而不管写入进程写入管道的数据块的大小是多少。

  4.通过管道传递的数据是顺序的,从管道中读取出来的字节的顺序和它们被写入管道的顺 序是完全一样的。

  5.在管道中的数据的传递方向是单向的,一端用于写入,一端用于读取,管道是半双工的。

  6.从管道读数据是一次性操作,数据一旦被读走,它就从管道中被抛弃,释放空间以便写 更多的数据,在管道中无法使用 lseek() 来随机的访问数据。

  7.匿名管道只能在具有公共祖先的进程(父进程与子进程,或者两个兄弟进程,具有亲缘 关系)之间使用。

  8.管道的数据结构是逻辑上的环形队列,由读指针和写指针操作

3.匿名管道相关指令和匿名管道创建

ulimit -a//查看管道缓冲区大小命令
long fpathconf(int fd, int name); //查看管道缓冲大小函数
//name为可选宏参数
_PC_PIPE_BUF //为查看缓冲大小

   这里缓冲区大小为8块512字节,一共4096字节。

  创建匿名管道

/*

        #include 
        int pipe(int pipefd[2]);
        作用:创建一个匿名管道用作进程间的通信,
        参数:
            int pipefd[]数组为传出参数(即函数存),存放两个文件描述符
                pipefd[0]对应管道读端
                pipefd[1]对应管道写端
        返回值:
            -成功:0
            -失败:-1
        #########匿名管道只能在有亲缘关系的进程中通信
        #########管道默认是阻塞的,若管道无数据,read阻塞,若管道已满,write阻塞
*/

#include 
#include 
#include wait.h>
#include 
#include
#include<string.h>

//子进程发送数据给父进程,父进程读取到数据进行输出
int main(){
    //在父子进程创建之前创建管道
    int pipefd[2];
    int pipefd1[2];
    int ret = pipe(pipefd);
    int ret1 = pipe(pipefd1);
    if(ret==-1||ret1==-1){
        perror("pipe");
        exit(0);
    }
    pid_t pid;
    pid = fork();
    //父进程
    if(pid>0){
        printf("i am parent pid:%d\n", getpid());
        char buf[1024] = {0};
        while(1){
            //父进程管道1读取,管道2写入
            int len = read(pipefd[0], buf, sizeof(buf));
            printf("parent recive : %s, pid:%d\n", buf, getpid());
            
            char * str = "hello, i am parent";
            write(pipefd1[1], str, strlen(str));
            sleep(1);
        }
    }
    //子进程
    else if(pid==0){
        printf("i am child pid:%d\n", getpid());
        char buf[1024] = {0};
        while(1){
            //子进程管道1写入,管道2读取
            char * str = "hello, i am child";
            write(pipefd[1], str, strlen(str));
            sleep(1);
            int len = read(pipefd1[0], buf, sizeof(buf));
            printf("child recive : %s, pid:%d\n", buf, getpid());
        }
        
    }
    return 0;

}

4.匿名管道读写特点

使用管道时,需注意(假设都是在I/O阻塞操作)  

  1.所有的写端都关闭了(管道写端引用计数为0),有进程从管道的读端读数据,那么管道中剩余的数据被读取后,再次读取就会返回0,就像已经读到了末尾一样

  2.如果写端没有全关闭(管道写端引用计数大于0),而持有管道写端的进程没有向管道中写数据,这时候有进程从管道中读取数据,此时会阻塞,直到写端写入数据

  3.如果读端都关闭了(管道读端引用计数为0),此时有进程向管道写数据,那么该进程会收到信号SIGPIPE,通常会导致进程异常终止

  4.如果读端没有全关闭(管道读端引用计数大于0),此时写入数据会阻塞,直到读端读取数据

总结:
读:
管道中有数据:read实际读到的
管道中无数据:
  写端全部关闭,read返回0
  写端有未关闭,read阻塞等待
写:
管道读端全关闭,进程会异常终止(进程受到SIGPIPE信号)
管道读端没有全部关闭:
  管道已满,阻塞
  管道未满,进行写入

 2.有名管道通信

  有名管道(FIFO)与匿名管道大部分特点一致,除了:

  1.FIFO在文件系统中作为一个特殊文件存在,但 FIFO中的内容却存放在内存中。

  2.当使用FIFo的进程退出后,FIFO文件将继续保存在文件系统中以便以后使用。

  3.FIFO有名字,不相关的进程可以通过打开有名管道进行通信。

2.1 有名管道的创建

  创建有名管道文件fifo:

  1.通过命令mkfifo name

  2.通过函数int mkfifo(const char *pathname, mode_t mode);
/*
    创建有名管道文件fifo:
    1.通过命令mkfifo name
    2.通过函数int mkfifo(const char *pathname, mode_t mode);

        #include 
        #include 

        int mkfifo(const char *pathname, mode_t mode);
            -作用:创建有名管道文件
            -参数:
                -pathname:管道路径名称
                -mode:同open函数的mode,设定管道文件的权限(,8进制,注意与掩码反码按位与)
            -返回值:
                成功:0
                失败:-1
*/
#include 
#include 
#include 
#include 
#include 
#include
#include<string.h>

int main(){
    //判断文件是否存在
    int ret1 = access("fifo1",F_OK);
    if(ret1==-1){
        printf("文件不存在,创建");
        int ret = mkfifo("fifo1", 0664);
        if(ret == -1){
            perror("mkfifo");
            exit(0);
        }
    }
    return 0;
}

2.2 有名管道的通信

 有名管道注意事项:         1、一个为只读而打开一个管道的进程会阻塞,直到另一个进程为只写打开管道         2、一个为只写而打开一个管道的进程会阻塞,直到另一个进程为只读打开管道     读管道:         1、有数据返回实际读到的数据         2、无数据:             -写端全部关闭:返回0,相当于读到文件末尾             -写端没有全部关闭:阻塞     写管道:         1、读端被全部关闭,进程会异常终止(sigpipe信号)         2、读端没有全部关闭:             管道已满:会阻塞             管道没有满:写入数据并返回实际写入字节数
/*
    向有名管道写数据
*/
#include 
#include 
#include 
#include 
#include 
#include
#include 
#include<string.h>

//向管道中写数据

int main(){
    //判断文件是否存在
    int ret1 = access("fifo1",F_OK);
    if(ret1==-1){
        printf("文件不存在,创建");
        //创建管道文件
        int ret = mkfifo("fifo1", 0664);
        if(ret == -1){
            perror("mkfifo");
            exit(0);
        }
    }
    //以只写方式打开管道
    int fd = open("fifo1", O_WRONLY);
    if(fd==-1){
        perror("open");
        exit(0);
    }
    
    for(int i =0;i<100;++i){
        char buf[1024];
        sprintf(buf,"hello: %d\n", i);
        printf("write date: %s\n", buf);
        write(fd, buf, strlen(buf));
        sleep(1);
    }
    close(fd);

    return 0;
}
/*
    从有名管道读数据

*/

#include 
#include 
#include 
#include 
#include 
#include
#include 
#include<string.h>

//从管道中读数据
int main(){
    //1.打开管道文件
    int fd = open("fifo1", O_RDONLY);
    if(fd ==-1){
        perror("open");
        exit(0);
    }
    //2.读数据
    while(1){
        char buf[1024] = {0};
        int len = read(fd, buf, sizeof(buf));
        //如果写端已经关闭
        if(len==0){
            printf("写端断开连接了.....\n");
            break;
        }
        printf("recv buf: %s\n", buf);
    }
    //3.关闭文件描述符
    close(fd);
    return 0;
}

 2.3 使用有名管道完成简单的进程间聊天

   功能为进程A和进程B之间依次交替发送和接收,不连续发送和接收(利用两根管道),流程如下:

代码:

进程A :

#include 
#include 
#include 
#include 
#include 
#include
#include 
#include<string.h>

//进程A
int main(){
    //1.判断有名管道文件是否存在(管道1)
    int ret = access("fifo1",F_OK);
    if(ret==-1){
        printf("管道不存在,创建对应管道\n");
        ret = mkfifo("fifo1", 0664);
        if(ret == -1){
            perror("mkfifo");
            exit(0);
        }
    }
    //2.判断有名管道文件是否存在(管道2)
    ret = access("fifo2",F_OK);
    if(ret==-1){
        printf("管道不存在,创建对应管道\n");
        ret = mkfifo("fifo2", 0664);
        if(ret == -1){
            perror("mkfifo");
            exit(0);
        }
    }
    //3.以只写的方式打开管道1
    int fdw = open("fifo1", O_WRONLY);
    if(fdw==-1){
        perror("open");
        exit(0);
    }
    printf("打开FIFO1成功,等待写入数据\n");
    //4.以只读的方式打开管道2
    int fdr = open("fifo1", O_RDONLY);
    if(fdr==-1){
        perror("open");
        exit(0);
    }
    printf("打开fifo2成功,等待读取数据\n");
    char buf[128];
    //4.循环写读数据
    while(1){
        //获取标准输入
        memset(buf, 0, 128);
        fgets(buf, 128, stdin);
        //写数据
        ret = write(fdw, buf ,strlen(buf));
        if(ret == -1){
            perror("write");
            exit(0);
        }
        //等待读取管道2数据
        memset(buf, 0, 128);
        ret = read(fdr, buf, 128);
        //如果没有可读取数据
        if(ret<=0){
            perror("read:");
            break;
        }
        printf("get: %s\n", buf);

    }
    //关闭文件描述符
    close(fdw);
    close(fdr);

    return 0;
}

进程B:

#include 
#include 
#include 
#include 
#include 
#include
#include 
#include<string.h>

//进程B
int main(){
    //1.判断有名管道文件是否存在(管道1)
    int ret = access("fifo1",F_OK);
    if(ret==-1){
        printf("管道不存在,创建对应管道\n");
        ret = mkfifo("fifo1", 0664);
        if(ret == -1){
            perror("mkfifo");
            exit(0);
        }
    }
    //2.判断有名管道文件是否存在(管道2)
    ret = access("fifo2",F_OK);
    if(ret==-1){
        printf("管道不存在,创建对应管道\n");
        ret = mkfifo("fifo2", 0664);
        if(ret == -1){
            perror("mkfifo");
            exit(0);
        }
    }
    //3.以只读的方式打开管道1
    int fdr = open("fifo1", O_RDONLY);
    if(fdr==-1){
        perror("open");
        exit(0);
    }
    printf("打开FIFO1成功,等待读取数据\n");
    //4.以只写的方式打开管道2
    int fdw = open("fifo1", O_WRONLY);
    if(fdw==-1){
        perror("open");
        exit(0);
    }
    printf("打开fifo2成功,等待写入数据\n");
    char buf[128];
    //4.循环读写数据
    while(1){
        //等待读取管道2数据
        memset(buf, 0, 128);
        ret = read(fdr, buf, 128);
        //如果没有可读取数据
        if(ret<=0){
            perror("read:");
            break;
        }
        printf("get: %s\n", buf);
        //获取标准输入
        memset(buf, 0, 128);
        fgets(buf, 128, stdin);
        //写数据
        ret = write(fdw, buf ,strlen(buf));
        if(ret == -1){
            perror("write");
            exit(0);
        }
    }
    //关闭文件描述符
    close(fdw);
    close(fdr);

    return 0;
}

2.4. 有名管道+父子进程实现聊天功能

   使用g++,和gcc类似

  chaA:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include <string.h>
using namespace std;

//进程A
int main(){
    pid_t pid = fork();
    int ret;
    if(pid == -1){
        perror("fork");
        exit(0);
    }
    //A进程本身(父进程),实现管道一的写入
    else if(pid>0){
        ret = access("fifo1", F_OK);
        if(ret==-1){
            cout<<"管道不存在,创建对应管道"<<endl;
            ret = mkfifo("fifo1", 0664);
            //管道创建失败
            if(ret==-1){
                perror("fifo1");
                exit(0);
            }
        }
        //以只写的方式打开管道一
        int fdw = open("fifo1", O_WRONLY);
        //打开失败
        if(fdw==-1){
            perror("open");
            exit(0);
        }
        printf("打开FIFO1成功,等待写入数据\n");
        //循环写入
        char buf[128];
        while(1){
            memset(buf,0,128);
            cin.getline(buf,128);
            ret = write(fdw, buf, strlen(buf));
            if(ret == -1){
                perror("write");
                exit(0);
            }
            
        }
        close(fdw);
    }
    //A进程的子进程,实现管道二的读取
    else if (pid == 0){
        ret = access("fifo2", F_OK);
        if(ret==-1){
            cout<<"管道不存在,创建对应管道"<<endl;
            ret = mkfifo("fifo2", 0664);
            //管道创建失败
            if(ret==-1){
                perror("fifo2");
                exit(0);
            }
        }
        //以只读的方式打开管道2
        int fdr = open("fifo2", O_RDONLY);
        //打开失败
        if(fdr==-1){
            perror("open");
            exit(0);
        }
        cout<<"打开FIFO2成功,等待读取数据"<<endl;
        //循环读取
        char buf[128];
        while(1){
            memset(buf, 0, 128);
            ret = read(fdr, buf, 128);
            //如果没有可读取数据
            if(ret<=0){
                perror("read:");
                break;
            }
            cout<<"get:"<endl;
        }
        close(fdr);
    }
    return 0;
}

  chatB:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include <string.h>
using namespace std;

//进程B
int main(){
    pid_t pid = fork();
    int ret;
    if(pid == -1){
        perror("fork");
        exit(0);
    }
    //B进程本身(父进程),实现管道一的读取
    else if(pid>0){
        ret = access("fifo1", F_OK);
        if(ret==-1){
            cout<<"管道不存在,创建对应管道"<<endl;
            ret = mkfifo("fifo1", 0664);
            //管道创建失败
            if(ret==-1){
                perror("fifo1");
                exit(0);
            }
        }
        //以只读的方式打开管道一
        int fdr = open("fifo1", O_RDONLY);
        //打开失败
        if(fdr==-1){
            perror("open");
            exit(0);
        }
        printf("打开FIFO1成功,等待读取数据\n");
        //循环读取
        char buf[128];
        while(1){
            memset(buf, 0, 128);
            ret = read(fdr, buf, 128);
            //如果没有可读取数据
            if(ret<=0){
                perror("read:");
                break;
            }
            cout<<"get:"<endl;
        }
        close(fdr);
    }
    //B进程的子进程,实现管道二的写入
    else if (pid == 0){
        ret = access("fifo2", F_OK);
        if(ret==-1){
            cout<<"管道不存在,创建对应管道"<<endl;
            ret = mkfifo("fifo2", 0664);
            //管道创建失败
            if(ret==-1){
                perror("fifo2");
                exit(0);
            }
        }
        //以只写的方式打开管道2
        int fdw = open("fifo2", O_WRONLY);
        //打开失败
        if(fdw==-1){
            perror("open");
            exit(0);
        }
        cout<<"打开FIFO2成功,等待写入数据"<<endl;
        //循环写入
        char buf[128];
        while(1){
            memset(buf,0,128);
            cin.getline(buf,128);
            ret = write(fdw, buf, strlen(buf));
            if(ret == -1){
                perror("write");
                exit(0);
            }
        }
        close(fdw);
    }
    return 0;
}

相关