chatA文件
#include<iostream>
using namespace std;
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdlib.h>
#include<string.h>
int main(int args,char*argv[]){
//创建两个管道,这个进程负责在pipe1中读,在pipe2中写,
//fork(),父进程负责pipe1中读,子进程负责pipe2中写
int fd1,fd2; //pipe1 pipe2文件描述符
if(access("pipe1",F_OK)==-1){
fd1=mkfifo("pipe1",0664);
if(fd1!=-1)
cout<<"管道pipe1创建成功"<<endl;
}
if(access("pipe2",F_OK)==-1){
fd2=mkfifo("pipe2",0664);
if(fd2!=-1)
cout<<"管道pipe2创建成功"<<endl;
}
pid_t pid=fork(); //创建子进程
if(pid>0){ //父进程pipe1 读
fd1=open("pipe1",O_RDONLY);
char buf[100];
while(1){
int len=read(fd1,buf,sizeof(buf));
cout<<buf<<endl;
memset(buf,0,sizeof(buf));
}
}else{
char buf[100];
fd2=open("pipe2",O_WRONLY);
while(1){
cin>>buf;
write(fd2,buf,sizeof(buf));
}
}
}
chatB文件
#include<iostream>
using namespace std;
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdlib.h>
#include<string.h>
int main(int args,char*argv[]){
//创建两个管道,这个进程负责在pipe1中写,在pipe2中读,
//fork(),父进程负责pipe1中写,子进程负责pipe2中读
int fd1,fd2; //pipe1 pipe2文件描述符
if(access("pipe1",F_OK)==-1){
fd1=mkfifo("pipe1",0664);
if(fd1!=-1)
cout<<"管道pipe1创建成功"<<endl;
}
if(access("pipe2",F_OK)==-1){
fd2=mkfifo("pipe2",0664);
if(fd2!=-1)
cout<<"管道pipe2创建成功"<<endl;
}
pid_t pid=fork(); //创建子进程
if(pid>0){ //父进程pipe1 写
char buf[100];
fd1=open("pipe1",O_WRONLY);
while(1){
cin>>buf;
write(fd1,buf,sizeof(buf));
}
}else{
fd2=open("pipe2",O_RDONLY);
char buf[100];
while(1){
int len=read(fd2,buf,sizeof(buf));
cout<<buf<<endl;
memset(buf,0,sizeof(buf));
}
}
}