#include<stdio.h>#include<stdlib.h>#include<sys/types.h>//the two head files are concerned with int mkfifo(const char *pathname, mode_t mode).#include<sys/stat.h>#include<fcntl.h>#include<unistd.h>#include<string.h>#include<time.h>//use time(time_t *ptr) to get different time from 1970.1.1.00:00 to make srand(unsigned int seed) function produce different seed.a#defineLEN230int length_total=0;//additional l or L represent it's a long integer.voidperform(int sig);voidset_data(char*ptrbuf,int len);intmain(){remove("fifo1");//unlink("fifo") function deletes a fifo pipeunlink("fifo2");int ret1 =mkfifo("fifo1",0644),
ret2 =mkfifo("fifo2",0644);if((ret1 <0)||( ret2 <0)){perror("make fifo error");exit(1);}int fd1 =open("fifo1",O_WRONLY),//open the pipes
fd2 =open("fifo2",O_RDONLY);if((fd1 <0)||(fd2 <0)){perror("open fifo error");exit(1);}char buf1[BUFSIZ];//BUFSIZ=8192 Bytesint timer=0;signal(SIGINT,perform);for(;;){time_t t;char buf_time[20];time(&t);ctime_r(&t,buf_time);//get the time difference from 1970srand((unsignedint)time(NULL));//different seeds make different random sequence.int timer,len=rand()%(BUFSIZ/sizeof(char)/10-10)+1;//BUFSIZ/sizeof(char)-10/*set data in buf array*/set_data(buf1,len);printf("seq=%d\nlength=%dbytes\ntime=%sdata:%s\n",++timer,(int)(len*sizeof(char)),buf_time,buf1);write(fd1,buf1,len);//write into pipe
length_total+=len;sleep(2);char buf2[LEN2]={0};int rd2=read(fd2,buf2,LEN2);if(rd2 >0){printf("I'm receiving the result......\n");sleep(2);printf("%s\nreceive success!\n\n\n",buf2);}sleep(1);}return0;}voidset_data(char*ptrbuf,int len){int i,val=0;for(i=0;i<len-1;i++){if(0==rand()%2){
ptrbuf[i]='0';
val^=0;}else{
ptrbuf[i]='1';
val^=1;}}
ptrbuf[i++]=(char)(48+val);
ptrbuf[i]='\0';}voidperform(int sig){printf("Send %d bytes data in total!\n",length_total);signal(sig,SIG_DFL);kill(getpid(),SIGINT);}
fifo_read.c
#include<stdio.h>#include<stdlib.h>#include<sys/types.h>//the two head files are concerned with int mkfifo(const char *pathname, mode_t mode).#include<sys/stat.h>#include<fcntl.h>#include<unistd.h>#include<string.h>#include<time.h>#defineLEN230voidfeedback(int flag);intmain(){int fd1 =open("fifo1",O_RDONLY),
fd2 =open("fifo2",O_WRONLY);if((fd1 <0)||(fd2 <0)){perror("open fifo error");exit(1);}int timer=0;while(1){time_t t;char buf_time[20];time(&t);ctime_r(&t,buf_time);//get the time difference from 1970char buf1[BUFSIZ]={0};int ret1 =read(fd1,buf1,sizeof(buf1)),
sign=0,
len=strlen(buf1);if(ret1>0){printf("seq=%d\nlength=%dbytes\ntime=%sdata:%s\n",++timer,(int)(len*sizeof(char)),buf_time,buf1);int i;for(i=0;i<len-1;i++){sign^=(buf1[i]-48);}if(sign+48==buf1[i]){printf("Check right!\nThe check result is sending......");char buf2[LEN2]="Check right!";write(fd2,buf2,LEN2);}else{printf("Check wrong!\nThe check result is sending......");char buf2[LEN2]="Check wrong!";write(fd2,buf2,LEN2);}sleep(1);printf("\nsend success!\n\n\n");}}return0;}