Linux c==进程通信--有名管道(4)
来源:互联网 发布:ios的编程框架 编辑:程序博客网 时间:2024/06/06 11:49
命名管道和无名管道基本相同,但也有不同点:
无名管道只能由父子进程使用;
但是通过命名管道,不相关的进程也能交换数据。
命名管道的使用
创建管道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 c==进程通信--有名管道(4)
- linux进程通信-有名管道
- linux进程通信--有名管道
- linux进程通信----FIFO(有名管道)
- linux进程间通信之有名管道
- 进程通信--有名管道
- Linux C 父子进程 与 有名管道
- linux有名管道通信
- Linux环境进程间通信:管道及有名管道
- Linux进程间通信:管道及有名管道
- Linux环境进程间通信:管道及有名管道
- Linux环境进程间通信: 管道及有名管道
- Linux环境进程间通信:管道及有名管道
- Linux进程间通信:管道及有名管道 收藏
- Linux--进程间通信(管道及有名管道FIFO)
- linux进程通信机制之无名管道&有名管道
- Linux--进程间通信(管道及有名管道FIFO)
- Linux--进程间通信(管道及有名管道FIFO)
- 第一个缓冲区溢出的全过程实践
- delphi2007 打开项目时,突然报错,提示microsoft.net borland 报错
- AIM Tech Round 3 (Div. 1)-B. Recover the String
- codeforces 43C Lucky Tickets
- 关于eclipse启动报错An internal error occurred during: "reload maven project". java.lang.NullPointerExcepti
- Linux c==进程通信--有名管道(4)
- 数据结构实验之二叉树六:哈夫曼编码
- 【微信小程序】从入门到放弃
- JavaScript权威指南之闭包
- Problem 3 Largest prime factor (分解素因子)
- contentprovider的学习实例总结
- oracle中的分页
- contentprovider的学习实例总结(摘抄)
- 字符串笔试题