Linux学习笔记-匿名和命名管道读写的相同点及不同点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/86103432

目录

 

 

理论

例子


 

理论

匿名和命名管道读写的相同性

1.默认都是阻塞性读写;

2.都适用于socket的网络通信;

3.阻塞不完整管道(有一段关闭)

a.单纯读时,在所有数据被读取后,read返回0,以表示到达了文件尾部。

b..单纯写时,则产生信号SIGPIPE,如果忽略该信号或捕捉该信号并从处理程序返回,则write返回-1,同时errno设置为EPIPE。

4.阻塞完整管道(两端都开启)

a.单纯读时,要么阻塞,要么读取到数据。

b.单纯写时,写到管道满时会出错。

5.非阻塞不完整管道(有一端关闭)

a.单纯读时直接报错;

b.单纯写时,则产生信号SIGPIPE,如果忽略该信号或捕捉该信号并从处理程序返回,则write返回-1,则同时errno设置为EPIPE。

6.非阻塞完整管道(两端都开启)

a.单纯读时直接报错;

b.单纯写时,写到管道时会出错;

 

不同点

1.打开方式不一致;

2.pipe通过fcntl系统设置O_NOBLOCK来设置非阻塞性读写;

3.FIFO通过fcntl系统调用或者open函数来设置非阻塞;

 

例子

FIFO通过fcntl系统调用或者open函数来设置非阻塞性读写

如下的源码:

fifo_read.c

#include <stdlib.h>
#include <fcntl.h>
#include <memory.h>

int main(int argc, char *argv[]){

        if(argc < 2){

                printf("usage:%s fifo\n", argv[0]);
                exit(1);
        }

        printf("open fifo read... \n");

        //int fd = open(argv[1], O_RDONLY);
        int fd = open(argv[1], O_RDONLY | O_NONBLOCK);
        if(fd < 0){

                perror("open error");
                exit(1);
        }
        else{

                printf("open file success:%d\n", fd);
        }

        //从命名管道中读取数据
        char buf[512];
        memset(buf, 0, sizeof(buf));
        while(read(fd, buf, sizeof(buf)) < 0){

                perror("read error");
        }
        printf("%s\n", buf);

        close(fd);
        exit(0);
}

运行截图如下:

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/86103432