博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
进程通信之有名管道
阅读量:4298 次
发布时间:2019-05-27

本文共 2282 字,大约阅读时间需要 7 分钟。

1、无名管道只能用于有亲缘关于的进程通信,有名管道可以实现无亲缘关系的通信

2、有名管道fifo 给文件系统提供一个路径,这个路径和管道关联,只要知道这个管道路径,就可以进行文件访问,fifo 

是指先进先出,也就是先写入的数据,先读出来

3、有名管道的读写速度非常快

4、man 3 mkfifo

5、int mkfifo(const char *pathname, mode_t mode)

     –参数*pathname:路径名,管道名称
     –参数mode:管道的权限
     –返回值:成功返回0,错误返回-1并更改errno的值。errno有可能出现的值为EACCESS EEXIST ENAMETOO-LONG ENOENT ENOENT ENOSPE ENOTDIR EROFS

例:

1、创建管道

#include
#include
#include
#include
#include
int main (int argc, char *argv[]){ mode_t mode = 0666; /*新创建的FIFO模式*/ if(argc != 2) { printf( "USEMS: create_fifo {fifoname}\n"); exit(1); } /*使用mkfifo()函数创建一个FIFO管道*/ if((mkfifo(argv[1],mode)) < 0) { perror("fail to mkfifo"); exit(1); }else{ printf("you successfully create a FIFO name is:%s\n",argv[1]); } exit(1);}
2、FIFO 的读写操作

open函数参数flag标志位的O_NONBLOCK标志,它关系到函数的返回状态。

O_NONBLOCK 
置位: 只读open立即返回。当只写open时,如果没有进程为读打开FIFO,则返回-1,并置errno值为ENXIO
不置位:open视情况阻塞。只读open要阻塞到进程为写打开FIFO,只写open要阻塞到有进程为读打开FIFO。

write_fifo.c

#include
#include
#include
#include
#include
#include
#include
#include
#define BUFSZ PIPE_BUF int main(void){ int fd; int n,i; char buf[BUFSZ]; time_t tp; printf("I am %d\n",getpid()); if((fd = open("fifo1",O_WRONLY)) < 0 { perror("open"); exit(1); } for(i = 0; i<10; i++) { time(&tp); n = sprintf(buf, "write_fifo %d sends %d", getpid(),ctime(&tp)); printf("send msg: %s\n",buf); if((write(fd,buf,n+1)) < 0) { perror("wrinte"); close(fd); exit(1); } sleep(3); } close(fd); exit(0);}

read_fifo.c

#include
#include
#include
#include
#include
#include
#include
#include
#define BUFSZ PIPE_BUFint main(void){ int fd; int n,i; char buf[BUFSZ]; mode_t mode = 0666; if((fd = open("fifo1",O_RDONLY)) < 0 { perror("open"); exit(1); } while((len = read(fd,buf,BUFSZ)) > 0); printf("read_fifo read :%s",buf); close(fd); exit(0);}

$gcc write_fifo.c -o write_fifo

$gcc read_fifo.c -o read_fifo
$mkfifo -m 666 fifo1
$./write_fifo
I am 16414
Send msg :write_fifo 16414 sends Fri Mar 22 15:48:54 2013
$./read_fifo
read_fifo read:write_fifo 16414 sends Fri Mar 22 15:48:54 2013

转载地址:http://aynws.baihongyu.com/

你可能感兴趣的文章
<rich:modelPanel>标签的使用
查看>>
<h:commandLink>和<h:inputLink>的区别
查看>>
<a4j:keeyAlive>的英文介绍
查看>>
关于list对象的转化问题
查看>>
VOPO对象介绍
查看>>
suse创建的虚拟机,修改ip地址
查看>>
linux的挂载的问题,重启后就挂载就没有了
查看>>
docker原始镜像启动容器并创建Apache服务器实现反向代理
查看>>
docker容器秒死的解决办法
查看>>
管理网&业务网的一些笔记
查看>>
openstack报错解决一
查看>>
openstack报错解决二
查看>>
linux source命令
查看>>
openstack报错解决三
查看>>
乙未年年终总结
查看>>
子网掩码
查看>>
第一天上班没精神
查看>>
启动eclipse报错:Failed to load the JNI shared library
查看>>
eclipse安装插件的两种方式在线和离线
查看>>
linux下源的相关笔记(suse)
查看>>