两个源文件,一个创建fifo文件并向其中写入,另一个往外读。
写文件:
/*********Ii****************************************************************
> File Name: fifo_test_01.c
> Author: xuchen_allen
> Mail: xuchen_allen@163.com
> Created Time: 2019年02月01日 星期五 17时58分03秒
************************************************************************/
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
//fifo 匿名管道基础运用:
//这个源文件是创建一个fifo_file文件,并向其中写入数据;
int main(void)
{
pid_t pid;
printf("\nthis process is NO %d\n",getpid());
char *buf[2048];
//创建一个fifo file 文件
int ret=0;
if((ret=mkfifo("fifo_test",0644))<0){
perror("mkfifo fail");
exit(1);
}
printf("ret=%d\n",ret);
//打开一个文件:
int data_fd;
data_fd=open("test",O_RDONLY);
if(data_fd<0){
perror("open fail;");
exit(1);
}
printf("data_fd=%d\n,",data_fd);
//打开fifo文件:
// int fifo_fd=open("fifo_test",O_WRONLY|O_NONBLOCK); printf("fifo_fd=%d",fifo_fd);//非阻塞的直接返回-1;
int fifo_fd=open("fifo_test",O_WRONLY);
// printf("fifo_fd=%d",fifo_fd);
if(fifo_fd<0){
perror("open fifo fail:");
exit(1);
}
printf("fifo_fd=%d\n",fifo_fd);
//从data_fd中读出数据,写入fifo_fd中:
int n=read(data_fd,buf,2048);
if(n<0){
perror("read fail:");
exit(1);
}
printf("n=%d\n",n);
if(write(fifo_fd,buf,n)<0){
perror("write fail");
exit(1);
}
/*
if(write(STDOUT_FILENO,buf,n)<0){
perror("asd");
exit(1);
}
*/
close(data_fd);
close(fifo_fd);
exit(0);
}
读文件:
/*************************************************************************
> File Name: fifo_test_01_read.c
> Author: xuchen_allen
> Mail: xuchen_allen@163.com
> Created Time: 2019年02月01日 星期五 19时56分38秒
************************************************************************/
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
//读取之前创建的fifo_test文件:
int main(void)
{
pid_t pid;
int fifo_fd;
char *buf[2048];
printf("\nasdasdasdasd");
//标准输出打印出来:
fifo_fd = open("fifo_test",O_RDONLY);
//将写入fifo的数据读取出来:
int n = read(fifo_fd,buf,2048);
//输出到屏幕上:
printf("\n");
write(STDOUT_FILENO,buf,n);
printf("\nthe process is NO %d\n",getpid());
close(fifo_fd);
exit(0);
}
在执行时,先:
./write_app &
再:
./read_app &
就能看到全部输出。
另外,写文件里加了一些额外输出,可以看到阻塞mode下的情况。