代码解析:
- 本题中使用mkfifo pipefile 在命令行状态下创建管道文件。
- 首先执行读文件程序,对第三方缓冲区内的内容进行读取操作。
- 对传入参数进行判断,是否含有管道文件的路径。如有函数继续运行,无则结束运行。
- 获取管道的路径信息,命令行输出管道信息,调用open打开FIFO文件(命名管道),停止执行,等待另一个open函数调用时唤醒。
- 执行写文件程序,正确获取到管道路径信息后,调用open打开FIFO文件,唤醒读文件程序继续执行,两个程序并行。读文件程序打印FIFO打开成功,写文件程序打印FIFO打开成功。
- 写程序进入睡眠,读程序运行至read时等待写程序调用write执行写操作向第三方缓存写数据,写程序沉睡结束调用write,写入信息成功,读程序获取到缓存中的数据,写程序打印写入成功并正常退出。读程序打印获取到的数据并正常退出。
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
//写端
int main(int argc,char *argv[]){
if (argc !=2){
printf("not enough params,give pipefile name\n");
exit(1);}
char *pipefile;
pipefile=argv[1];
int fd;
char *teststr="test strings!";
printf("OPEN namedpipe--%s for write!\n",pipefile);
fd=open(pipefile,O_WRONLY,0);//打开管道
printf("OK!namedpipe--%s opened for write!\n",pipefile);
//sleep(5);
write(fd,teststr,strlen(teststr));//写入信息
printf("OK!namedpipe write successfully!\n");
exit(0);
}
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
//读端
int main(int argc,char *argv[]){
if (argc !=2) {
printf("not enough params,give pipefile name\n");
exit(1);}
char *pipefile;
pipefile=argv[1];
char buf[100];
int fd,i;
printf("read open namedpipe!!\n");
fd=open(pipefile,O_RDONLY,0);
if (fd<0) {
printf("no such namedpipe file !!\n");
exit(-1); }
printf("OK!namedpipe opened for read!\n");
sleep(5);
i=read(fd,buf,100);
buf[i]=0;
printf("OK!readed from namedpipe: %s!\n",buf);
return 0;
}