Skip to content

Latest commit

 

History

History
746 lines (557 loc) · 20.9 KB

10、进程间通信.md

File metadata and controls

746 lines (557 loc) · 20.9 KB

进程间通信

为什么需要进程间通信

进程是一个独立的资源分配单元,不同进程(这里所说的进程通常指的是用户进程)之间的资源是独立的,没有关联,不能在一个进程中直接访问另一个进程的资源。

但是进程之间不是孤立的,不同进程之间需要进行信息交换和状态传递,因此需要进程间通信( IPC:Inter Processes Communication )。

进程通信的目的

  • 数据传输:一个进程需要将他的数据发给另外一个进程
  • 通知事件:一个进程需要向另一个进程或者进程组发生了某一事件
  • 资源共享:多个进程之间共享同样的资源,内核需要提供互斥和同步机制
  • 进程控制:有的进程需要完全控制另外一个进程,此时控制的进程需要拦截另外一个进程所有的陷入和异常并及时知道他的状态改变

进程通信的方式

image-20220811202841803

管道

什么是管道

管道也叫无名(匿名)管道,它是是 UNIX 系统 IPC(进程间通信)的最古老形式,所有的 UNIX 系统都支持这种通信机制。

统计一个目录中文件的数目命令:ls | wc –l,为了执行该命令,shell 创建了两个进程来分别执行 ls 和 wc。

image-20220812093613191

管道的特点

  • 管道是一个在内核内存中维护的缓冲器,缓冲器存储能力有限,不同操作系统大小不同

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

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

  • 通过管道传递的数据是顺序的,从管道中读取出来字节的顺序和被写入管道的顺序是完全一样的(类似一个队列)

  • 管道中数据传递方向是单向的,一端写入一端读取,是半双工的

  • 管道读数据是一次性的,数据一旦被读走就被抛弃释放空间,在管道中无法使用lseek()来随机访问数据

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

image-20220812100933061

tips:

  • 单工:指数据传输只支持数据在一个方向上传输

  • 双工:指二台通讯设备之间,允许有双向的资料传输。通常有两种双工模式。一种叫半双工,另一种叫全双工

  • 全双工:(full-duplex)的系统允许二台设备间同时进行双向数据传输。一般的电话、手机就是全双工的系统,因为在讲话时同时也可以听到对方的声音。

  • 半双工:(half-duplex)的系统允许二台设备之间的双向数据传输,但不能同时进行。因此同一时间只允许一设备传送资料,若另一设备要传送资料,需等原来传送资料的设备传送完成后再处理。

为什么可以使用管道进行进程间通信

可以从文件描述符的角度来看,对于两个亲缘关系的进程,他们往往共享一个文件描述符号表,因此他们可以对同一个文件进行读写操作。 管道不过是把文件描述符表的文件换成了管道。

image-20220812101131359

对于上图而言,左边进程文件描述符5指向管道写入端,6指向管道读取端这件事同样发生在fork出来的子进程当中,因此他们可以通过管道进行进程间通信(例如父进程从5写入,子进程从6读取)

image-20220812102440087

管道的数据结构

管道的数据结构在逻辑上是一个循环队列。 好处就是能避免普通队列假溢出问题,有效利用空间。 当然这是逻辑上的,内存上并非环形的。 管道的数据结构造成了管道的很多性质,比如只能读取一次啊,不能lseek随机访问啊之类的

image-20220812102548922

管道的使用

创建匿名管道

#include <unistd.h>
int pipe(int pipefd[2]);
/*
    #include <unistd.h>
    int pipe(int pipefd[2]);
        功能:创建一个匿名管道,用来进程间通信。
        参数:int pipefd[2] 这个数组是一个传出参数。
            pipefd[0] 对应的是管道的读端
            pipefd[1] 对应的是管道的写端
        返回值:
            成功 0
            失败 -1

    管道默认是阻塞的:如果管道中没有数据,read阻塞,如果管道满了,write阻塞

    注意:匿名管道只能用于具有关系的进程之间的通信(父子进程,兄弟进程)
*/

// 子进程发送数据给父进程,父进程读取到数据输出
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    // 在fork之前创建管道
    int pipefd[2];
    int ret = pipe(pipefd);
    if(ret == -1) {
        perror("pipe");
        exit(0);
    }

    // 创建子进程
    pid_t pid = fork();
    if(pid > 0) {
        // 父进程
        printf("i am parent process, pid : %d\n", getpid());

        // 关闭写端
        close(pipefd[1]);
        
        // 从管道的读取端读取数据
        char buf[1024] = {0};
        while(1) {
            int len = read(pipefd[0], buf, sizeof(buf));
            printf("parent recv : %s, pid : %d\n", buf, getpid());
            
            // 向管道中写入数据
            //char * str = "hello,i am parent";
            //write(pipefd[1], str, strlen(str));
            //sleep(1);
        }

    } else if(pid == 0){
        // 子进程
        printf("i am child process, pid : %d\n", getpid());
        // 关闭读端
        close(pipefd[0]);
        char buf[1024] = {0};
        while(1) {
            // 向管道中写入数据
            char * str = "hello,i am child";
            write(pipefd[1], str, strlen(str));
            //sleep(1);

            // int len = read(pipefd[0], buf, sizeof(buf));
            // printf("child recv : %s, pid : %d\n", buf, getpid());
            // bzero(buf, 1024);
        }
        
    }
    return 0;
}

image-20220812110452959

上面的程序有几个需要注意的点:

  1. read函数是阻塞的,所以如果你不往管道写入数据他是不会读的,因此父子进程读和写顺序不能相同,不然两个进程都在read函数阻塞了走不下去
  2. 每次写了数据后要清空buf,不然会出问题
  3. 被注释掉的部分,如果不加sleep,那么有可能父进程还没被CPU分配时间片,子进程就继续往下执行了,造成子进程读自己的写自己的情况(反过来的话就是父进程读自己写入的数据)
  4. 由于第三点,匿名管道一般不用来进行双向的通信,数据流向一般单向,我们一般会事先用close关闭父进程写端,子进程读端(对于这个例子而言)

查看管道缓冲大小

查看管道缓冲大小的shell命令:

ulimit –a

查看管道缓冲大小函数:

#include <unistd.h>
long fpathconf(int fd, int name);
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    int pipefd[2];

    int ret = pipe(pipefd);

    // 获取管道的大小
    long size = fpathconf(pipefd[0], _PC_PIPE_BUF);

    printf("pipe size : %ld\n", size);

    return 0;
}

匿名管道通信的案例

/*
    实现 ps aux | grep xxx 父子进程间通信
    
    子进程: ps aux, 子进程结束后,将数据发送给父进程
    父进程:获取到数据,过滤
    pipe()
    execlp()
    子进程将标准输出 stdout_fileno 重定向到管道的写端。  dup2
*/

#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wait.h>

int main() {

    // 创建一个管道
    int fd[2];
    int ret = pipe(fd);

    if(ret == -1) {
        perror("pipe");
        exit(0);
    }

    // 创建子进程
    pid_t pid = fork();

    if(pid > 0) {
        // 父进程
        // 关闭写端
        close(fd[1]);
        // 从管道中读取
        char buf[1024] = {0};

        int len = -1;
        while((len = read(fd[0], buf, sizeof(buf) - 1)) > 0) {
            // 过滤数据输出
            printf("%s", buf);
            memset(buf, 0, 1024);
        }

        wait(NULL);

    } else if(pid == 0) {
        // 子进程
        // 关闭读端
        close(fd[0]);

        // 文件描述符的重定向 stdout_fileno -> fd[1]
        dup2(fd[1], STDOUT_FILENO);
        // 执行 ps aux
        execlp("ps", "ps", "aux", NULL);
        perror("execlp");
        exit(0);
    } else {
        perror("fork");
        exit(0);
    }
    return 0;
}

管道的读写特点

    读管道:
        管道中有数据,read返回实际读到的字节数。
        管道中无数据:
            写端被全部关闭,read返回0(相当于读到文件的末尾)
            写端没有完全关闭,read阻塞等待

 	写管道:
        管道读端全部被关闭,进程异常终止(进程收到SIGPIPE信号)
        管道读端没有全部关闭:
            管道已满,write阻塞
            管道没有满,write将数据写入,并返回实际写入的字节数

因此,进行管道读写的时候要考虑清楚,读端写端的开启和关闭,如果读入过量数据会发生什么,是否需要循环多次读写

管道设置为非阻塞

管道的读端写端可以看作文件描述符,所以我们可以使用fctnl函数来设置管道是否阻塞。 首先获取原来的文件描述符的状态,然后让状态值或上非阻塞的宏得到新的文件描述符状态,最后重新设置文件描述符状态

#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
/*
    设置管道非阻塞
    int flags = fcntl(fd[0], F_GETFL);  // 获取原来的flag
    flags |= O_NONBLOCK;            // 修改flag的值
    fcntl(fd[0], F_SETFL, flags);   // 设置新的flag
*/
int main() {

    // 在fork之前创建管道
    int pipefd[2];
    int ret = pipe(pipefd);
    if(ret == -1) {
        perror("pipe");
        exit(0);
    }

        // 创建子进程
    pid_t pid = fork();
    if(pid > 0) {
        // 父进程
        printf("i am parent process, pid : %d\n", getpid());

        // 关闭写端
        close(pipefd[1]);
        
        // 从管道的读取端读取数据
        char buf[1024] = {0};

        int flags = fcntl(pipefd[0], F_GETFL);  // 获取原来的flag
        flags |= O_NONBLOCK;            // 修改flag的值
        fcntl(pipefd[0], F_SETFL, flags);   // 设置新的flag

        while(1) {
            int len = read(pipefd[0], buf, sizeof(buf));
            printf("len : %d\n", len);
            printf("parent recv : %s, pid : %d\n", buf, getpid());
            memset(buf, 0, 1024);
            sleep(1);
        }

    } else if(pid == 0){
        // 子进程
        printf("i am child process, pid : %d\n", getpid());
        // 关闭读端
        close(pipefd[0]);
        char buf[1024] = {0};
        while(1) {
            // 向管道中写入数据
            char * str = "hello,i am child";
            write(pipefd[1], str, strlen(str));
            sleep(5);
        }
        
    }
    return 0;
}

运行效果如下:

image-20220812131850490

子进程写入数据后,管道内有数据,父进程正常读数据。但是后面由于子进程sleep没有马上写入数据,管道内没有数据,父进程read原本应该被阻塞,但是因为我们设置了管道非阻塞,所以还是一直在读取。

有名管道

有名管道介绍

由于匿名管道没有名字,只能用于有亲缘关系的进程之间通信。为了克服这个缺点,出现了有名管道FIFO,也叫FIFO文件、命名管道。

有名管道提供了一个路径名与之关联,以FIFO的文件形式存在于文件系统之中,打开方式和普通文件一样,即使某个进程与FIFO的创建进程不存在亲缘关系,只要能访问该路径,就能通过FIFO相互通信。

一旦打开FIFO,操作基本就和匿名管道的操作一样了,同时也匿名管道一样有一个读端和一个写端,数据读取顺序和写入顺序一样

有名管道与匿名管道的区别

  1. FIFO在文件系统中作为一个特殊文件存在,但FIFO中的内容却存在内存中
  2. 当时用FIFO的进程退出后,FIFO文件继续保存在文件系统中,以后也可以使用
  3. FIFO有名字,不相关的进程可以打开有名管道通信

有名管道的使用

创建FIFO

通过命令创建有名管道

mkfifo +名字

通过函数创建有名管道

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

    #include <sys/types.h>
    #include <sys/stat.h>
    int mkfifo(const char *pathname, mode_t mode);
        参数:
            - pathname: 管道名称的路径
            - mode: 文件的权限 和 open 的 mode 是一样的
                    是一个八进制的数
        返回值:成功返回0,失败返回-1,并设置错误号

*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>

int main() {


    // 判断文件是否存在
    int ret = access("fifo1", F_OK);
    if(ret == -1) {
        printf("管道不存在,创建管道\n");
        
        ret = mkfifo("fifo1", 0664);

        if(ret == -1) {
            perror("mkfifo");
            exit(0);
        }       

    }
    return 0;
}
  • 一旦使用 mkfifo 创建了一个 FIFO,就可以使用 open 打开它,常见的文件I/O 函数都可用于 fifo。如:close、read、write、unlink 等。
  • FIFO 严格遵循先进先出(First in First out),对管道及 FIFO 的读总是从开始处返回数据,对它们的写则把数据添加到末尾。它们不支持诸如 lseek() 等文件定位操作
向管道写入数据
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main() {

    // 1.判断文件是否存在
    int ret = access("test", F_OK);
    if(ret == -1) {
        printf("管道不存在,创建管道\n");
        
        // 2.创建管道文件
        ret = mkfifo("test", 0664);

        if(ret == -1) {
            perror("mkfifo");
            exit(0);
        }       

    }

    // 3.以只写的方式打开管道
    int fd = open("test", 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 data : %s\n", buf);
        write(fd, buf, strlen(buf));
        sleep(1);
    }

    close(fd);

    return 0;
}

因为使用只写模式打开了管道,没有读端口打开,所以目前管道还是阻塞的,不会往里面写数据,所以下面还要整一个读端。

读取数据
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

// 从管道中读取数据
int main() {

    // 1.打开管道文件
    int fd = open("test", O_RDONLY);
    if(fd == -1) {
        perror("open");
        exit(0);
    }

    // 读数据
    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);
    }

    close(fd);

    return 0;
}

如果写端停掉,读端或报写端端口链接 如果读端停掉,写端会停下,产生信号了SIGPIPE

有名管道注意事项

1.一个为只读而打开一个管道的进程会阻塞,直到另外一个进程只写打开管道 2.一个为只写而打开一个管道的进程会阻塞,直到另外一个进程只读打开管道

读管道: 管道中有数据,read返回实际读到的字节数 管道中无数据: 管道写端被全部关闭,read返回0,(相当于读到文件末尾) 写端没有全部被关闭,read阻塞等待

写管道: 管道读端被全部关闭,进程异常终止(收到一个SIGPIPE信号) 管道读端没有全部关闭: 管道已经满了,write会阻塞 管道没有满,write将数据写入,并返回实际写入的字节数。

有名管道的使用

image-20220812191111518

进程A:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>

int main() {

    // 1.判断有名管道文件是否存在
    int ret = access("fifo1", F_OK);
    if(ret == -1) {
        // 文件不存在
        printf("管道不存在,创建对应的有名管道\n");
        ret = mkfifo("fifo1", 0664);
        if(ret == -1) {
            perror("mkfifo");
            exit(0);
        }
    }

    ret = access("fifo2", F_OK);
    if(ret == -1) {
        // 文件不存在
        printf("管道不存在,创建对应的有名管道\n");
        ret = mkfifo("fifo2", 0664);
        if(ret == -1) {
            perror("mkfifo");
            exit(0);
        }
    }

    // 2.以只写的方式打开管道fifo1
    int fdw = open("fifo1", O_WRONLY);
    if(fdw == -1) {
        perror("open");
        exit(0);
    }
    printf("打开管道fifo1成功,等待写入...\n");
    // 3.以只读的方式打开管道fifo2
    int fdr = open("fifo2", 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);
        }

        // 5.读管道数据
        memset(buf, 0, 128);
        ret = read(fdr, buf, 128);
        if(ret <= 0) {
            perror("read");
            break;
        }
        printf("buf: %s\n", buf);
    }

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

    return 0;
}

进程B:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>

int main() {

    // 1.判断有名管道文件是否存在
    int ret = access("fifo1", F_OK);
    if(ret == -1) {
        // 文件不存在
        printf("管道不存在,创建对应的有名管道\n");
        ret = mkfifo("fifo1", 0664);
        if(ret == -1) {
            perror("mkfifo");
            exit(0);
        }
    }

    ret = access("fifo2", F_OK);
    if(ret == -1) {
        // 文件不存在
        printf("管道不存在,创建对应的有名管道\n");
        ret = mkfifo("fifo2", 0664);
        if(ret == -1) {
            perror("mkfifo");
            exit(0);
        }
    }

    // 2.以只读的方式打开管道fifo1
    int fdr = open("fifo1", O_RDONLY);
    if(fdr == -1) {
        perror("open");
        exit(0);
    }
    printf("打开管道fifo1成功,等待读取...\n");
    // 3.以只写的方式打开管道fifo2
    int fdw = open("fifo2", O_WRONLY);
    if(fdw == -1) {
        perror("open");
        exit(0);
    }
    printf("打开管道fifo2成功,等待写入...\n");

    char buf[128];

    // 4.循环的读写数据
    while(1) {
        // 5.读管道数据
        memset(buf, 0, 128);
        ret = read(fdr, buf, 128);
        if(ret <= 0) {
            perror("read");
            break;
        }
        printf("buf: %s\n", buf);

        memset(buf, 0, 128);
        // 获取标准输入的数据
        fgets(buf, 128, stdin);
        // 写数据
        ret = write(fdw, buf, strlen(buf));
        if(ret == -1) {
            perror("write");
            exit(0);
        }
    }

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

    return 0;
}