代码一:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, const char *argv[])
{
//create a FIFO special file
if(argc<2){
printf("please enter 2 arguments\n");
printf("usage:./a.out fileName\n");
return -1;
}
int fifo;
if((fifo=mkfifo(argv[1],0664))==-1){
perror("mkfifo error");
return -1;
}
return 0;
}
代码二:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
if(argc<3){
printf("please enter no less than 3 arguments\n");
printf("usage:./a.out writeToFile readFromFile\n");
return -1;
}
pid_t pid;
if((pid=fork())==-1){
perror("process 1 fork error");
return -1;
}
//process 01 main process write info to pipe 01
if(pid>0){
int fd;
if((fd=open(argv[1],O_WRONLY))==-1){
perror("open fifo file 01 error");
exit(EXIT_FAILURE);
}
char buf[128]="";
while(strcmp(buf,"quit")!=0){
int res=read(0,buf,sizeof(buf));
buf[strlen(buf)-1]='\0';
write(fd,buf,res);
}
close(fd);
wait(NULL);
exit(EXIT_SUCCESS);
}
//process 01 new process read info from pipe 02
if(pid==0){
int fd;
if((fd=open(argv[2],O_RDONLY))==-1){
perror("open fifo file 02 error");
exit(EXIT_FAILURE);
}
char buf[128]="";
while(strcmp(buf,"quit")!=0){
int res=read(fd,buf,sizeof(buf));
buf[strlen(buf)-1]='\0';
printf(" process 01 new process read info from pipe 02---output\n");
write(1,buf,res);
}
close(fd);
exit(EXIT_SUCCESS);
}
return 0;
}
代码三:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
if(argc<3){
printf("please enter no less than 3 arguments\n");
printf("usage:./a.out writeToFile readFromFile\n");
return -1;
}
pid_t pid;
if((pid=fork())==-1){
perror("process 1 fork error");
return -1;
}
//process 01 main process write info to pipe 01
if(pid>0){
int fd;
if((fd=open(argv[1],O_WRONLY))==-1){
perror("open fifo file 01 error");
exit(EXIT_FAILURE);
}
char buf[128]="";
while(strcmp(buf,"quit")!=0){
int res=read(0,buf,sizeof(buf));
buf[strlen(buf)-1]='\0';
write(fd,buf,res);
}
close(fd);
wait(NULL);
exit(EXIT_SUCCESS);
}
//process 01 new process read info from pipe 02
if(pid==0){
int fd;
if((fd=open(argv[2],O_RDONLY))==-1){
perror("open fifo file 02 error");
exit(EXIT_FAILURE);
}
char buf[128]="";
while(strcmp(buf,"quit")!=0){
int res=read(fd,buf,sizeof(buf));
buf[strlen(buf)-1]='\0';
printf(" process 01 new process read info from pipe 02---output\n");
write(1,buf,res);
}
close(fd);
exit(EXIT_SUCCESS);
}
return 0;
}