#include<stdio.h>#include<stdlib.h>#include<fcntl.h>#include<string.h>#include<unistd.h>#defineN32intmain(){char buf[N];//定义一个数组int pfd;if((pfd =open("myfifo",O_WRONLY))<0)//open()打开管道文件,返回的是其文件描述符{//以只写方式打开perror("open");exit(-1);}printf("myfifo is open\n");while(1){fgets(buf,N,stdin);//从输入流stdin中读取32个字符到buf中if(strcmp(buf,"quit\n")==0)break;//若buf中字符为quit,则结束循环。不是则往下执行write(pfd,buf,N);//将buf中数据写入到管道中,写32位数据}close(pfd);//跳出循环时,关闭管道return0;}
第三步:读取有名管道中的数据( read_fifo.c)
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<fcntl.h>#include<string.h>#defineN32intmain(void){char buf[N];int pfd;if((pfd =open("myfifo",O_RDONLY))<0)//以只读方式打开管道文件,返回其文件描述符{perror("open");//出错时返回exit(-1);}printf("myfifo is opem");//写入端退出时,read()返回0,则退出循环nwhile(read(pfd,buf,N)>0){//读管道数据printf("the length of string is %d\n",strlen(buf));}close(pfd);//结束时关闭管道return0;}
book@100ask:~/process$ ./write_fifo //
myfifo is open //提示管道已打开
welcome to china //输入的字符串1
abc //输入的字符串21234//输入的字符串3
quit //结束
book@100ask:~/process$
********************************
book@100ask:~/process$ ./read_fifo
the length of string is 17//统计字符串1长度
the length of string is 4//统计字符串2长度
the length of string is 5//统计字符串3长度
book@100ask:~/process$