Linux命名管道

来源:互联网 发布:剑网三插件数据 编辑:程序博客网 时间:2024/05/22 14:17

命名管道实现了没有亲缘关系的进程的通信,创建命名管道时候,系统创建了一个FIFO的文件,通过对文件的操作,实现走了没有亲缘关系的管道也可以数据交换,相比普通管道

命名管道多了管道的打开和删除,因为是文件吗,当然剧本文件的属性了。

1.可以通过该shell命令创建命名管道,mknod 和mkfifo,比如通过命令创建命名管道p1;

mkfifo -m 0644 p1或者mknod p1 p;

2.系统提供了

int mkfifo (__const char *__path, __mode_t __mode);
管道的读写和文件无异,可以用open打开,两种方式打开阻塞(默认),非阻塞(open的标志设置为 O_NONBLOCK). 

在非阻塞模式下,对管道的只读打开立即返回,而如果实现没有进程以只读方式打开管道,则对管道的写方式打开返回失败,ENXIO.

阻塞模式:当打开一个管道读时,如果没有打开管道用于写的进程,则该打开操作将被阻塞,直道有一个进程用写的方式打开该管道为止。反之亦然。

案例

1.先以只读方式打开管道文件

#include<stdio.h>#include<unistd.h>#include<stdlib.h>#include<wait.h>#include<errno.h>#include<signal.h>#include <setjmp.h>#include<string.h>#include<sys/types.h>#include<fcntl.h>#include<sys/stat.h>/****以只读方式打开创建的管道p1,检测阻塞方式打开管道的过程*/// 会因为没有一个以写方式打开管道,卡住int main(){    int fd;    if((fd = open("/home/yy/p",O_RDONLY,0)) < 0)    {        perror("open");        exit(-1);    }    printf("open fifo p1 for read success!\n");    close(fd);    return 0;}

2.以只写方式打开同一个管道文件

#include<stdio.h>#include<unistd.h>#include<stdlib.h>#include<wait.h>#include<errno.h>#include<signal.h>#include <setjmp.h>#include<string.h>#include<sys/types.h>#include<fcntl.h>#include<sys/stat.h>/****以只读方式打开创建的管道p1,检测阻塞方式打开管道的过程*/// 在第一个例子没有的输出窗口没有退出的情况下,重新打开一个shell窗口允许这个,两个窗口都输出语句int main(){    int fd;    if((fd = open("/home/yy/p",O_WRONLY,0)) < 0)    {        perror("open");        exit(-1);    }    printf("open fifo p1 for read success!\n");    close(fd);    return 0;}



0 0
原创粉丝点击