1、
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./fifo1",0777)<0){
if(errno!=17){
perror("mkfifo");
return -1;
}
}
printf("create FIFO1 success\n");
if(mkfifo("./fifo2",0777)<0){
if(errno!=17){
perror("mkfifo");
return -1;
}
}
printf("create FIFO2 success\n");
//int fd= open("./fifo",O_RDONLY|O_NONBLOCK);
//int fd= open("./fifo",O_WRONLY|O_NONBLOCK);
pid_t pid=fork();
if(pid>0){
int fd= open("./fifo1",O_RDWR);
if(fd<0){
perror("open");
return -1;
}
printf("open success\n");
int fd2= open("./fifo2",O_RDWR);
if(fd2<0){
perror("open");
return -1;
}
printf("open success\n");
char buf[128]="";
ssize_t res;
while(1){
printf("父进程请输入:\n");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
if(write(fd,buf,sizeof(buf))<0){
perror("write");
return -1;
}
printf("write success\n");
if(!strcmp(buf,"quit")){
break;
}
bzero(buf,sizeof(buf));
res=read(fd2,buf,sizeof(buf));
if(res<0){
perror("read");
return -1;
}
else if(0==res){
printf("写入端全部关闭,且管道中没有数据\n");
break;
}
printf("res=%ld buf=%s\n",res,buf);
if(!strcmp(buf,"quit")){
break;
}
}
close(fd);
close(fd2);
wait(NULL);
}
else if(0==pid){
char buf[128]="";
int fd= open("./fifo1",O_RDWR);
if(fd<0){
perror("open");
return -1;
}
int fd2= open("./fifo2",O_RDWR);
if(fd2<0){
perror("open");
return -1;
}
ssize_t res;
while(1){
bzero(buf,sizeof(buf));
res=read(fd,buf,sizeof(buf));
if(!strcmp(buf,"quit")){
break;
}
if(res<0){
perror("read");
return -1;
}
else if(0==res){
printf("写入端全部关闭,且管道中没有数据\n");
break;
}
printf("res=%ld buf=%s\n",res,buf);
printf("子进程请输入:\n");
bzero(buf,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
if(write(fd2,buf,sizeof(buf))<0){
perror("write");
return -1;
}
printf("write success\n");
if(!strcmp(buf,"quit")){
break;
}
}
close(fd);
close(fd2);
}
else if(pid<0){
perror("fork");
return -1;
}
return 0;
}
2 b 线程
a线程