进程通信--有名管道
来源:互联网 发布:大数据销售 编辑:程序博客网 时间:2024/04/30 19:42
命名管道和无名管道基本相同,但也有不同点:
无名管道只能由父子进程使用;但是通过命名管道,不相关的进程也能交换数据。
命名管道的使用
创建管道mkfifo
打开管道open
读管道read
写管道write
关闭管道close
删除管道unlink
函数mkfifo
函数作用:创建有名管道
函数原型:int mkfifo(const char * pathname, mode_t mode);
函数参数:pathname:有名管道的路径,文件名 mode:属性(创建时,该文件必须不存在)
返回值 :成功返回0,出错:-1
头文件 :#include<sys/types.h>
#include<sys/stat.h>
函数unlink
函数作用:删除文件
函数原型:int unlink(const char * pathname);
函数参数:pathname : 文件路径+文件名
返回值 :成功 : 0;出错:-1
头文件 :
#include<unistd.h>
Fifo_wr.c
#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#define FIFO_SERVER "/tmp/myfifo"main(int argc,char** argv){ int fd; char w_buf[100]; int nwrite; /*打开管道*/ fd = open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0); if(argc == 1) { printf("Please send something\n"); exit(-1); } strcpy(w_buf,argv[1]); /* 向管道写入数据 */nwrite = write(fd,w_buf,100); if( nwrite== -1) { printf("The FIFO has not been read yet.Please try later\n"); } else printf("write %s to the FIFO\n",w_buf);}Fifo_rd.c#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#define FIFO "/tmp/myfifo"main(int argc,char** argv){ char buf_r[100]; int fd; int nread; /* 创建管道 */ //读写操作中只需要有一个文件中创建有名管道 if((mkfifo(FIFO,O_CREAT|O_EXCL) < 0) && (errno != EEXIST)) printf("cannot create fifoserver\n"); printf("Preparing for reading bytes...\n"); memset(buf_r,0,sizeof(buf_r)); /* 打开管道 */ fd = open(FIFO,O_RDONLY|O_NONBLOCK,0); if(fd == -1) { perror("open"); exit(1); } while(1) { memset(buf_r,0,sizeof(buf_r)); nread = read(fd,buf_r,100); if(nread == -1) { if(errno == EAGAIN) printf("no data yet\n"); } printf("read %s from FIFO\n",buf_r); sleep(1); } pause(); /*暂停,等待信号*/ unlink(FIFO); //删除文件}
FIFO文件在使用上和普通文件有相似之处,但是也有不有
不同之处:
1. 读取fifo文件的进程只能以”RDONLY”方式打开fifo文件。
2. 写fifo文件的进程只能以”WRONLY”方式打开fifo
3. fifo文件里面的内容被读取后,就消失了。但是普通文件里面的内容读取后还存在。
0 0
- 进程通信--有名管道
- 进程间通信--有名管道
- linux进程通信-有名管道
- 进程间通信-有名管道
- linux进程通信--有名管道
- 进程通信之有名管道
- 进程通信之有名管道
- 进程通信-有名管道FIFO
- 【进程通信】无名管道 and 有名管道
- linux进程通信----FIFO(有名管道)
- 进程间通信______有名管道(FIFO)
- 多进程间通信之有名管道
- 进程间通信方式之有名管道
- 进程间通信之有名管道
- 进程间通信编程(3) - 有名管道
- linux进程间通信之有名管道
- 进程间通信(二)有名管道
- 进程间通信(1)-有名管道
- Windows安装和使用zookeeper
- jenkins持续部署
- 团队项目开发——TFS
- 免费的域名和空间
- Android Studio如何使用GitHub上的开源项目
- 进程通信--有名管道
- Jquery - 页面刷新滚动条自动滚到最底下
- iOS开发 NSNotificationCenter 通知的使用方法
- C语言知识点-4
- 洛谷 P1069 细胞分裂
- av_reduce
- codeforces 721C journey(动态规划+拓扑排序)
- PE文件本地DLL注入实现
- JavaSE:1min讲解引用类型参数(2)-抽象类