creat.c
#include<myhead.h>
int main(int argc, char const *argv[])
{
//创建管道
if(mkfifo("./linux",0664)==-1)
{
perror("mkfifo error");
return -1;
}
getchar();
system("rm linux");
return 0;
}
sen.c
#include<myhead.h>
int main(int argc, char const *argv[])
{
//可写形式打开管道
int wfd=open("./linux",O_WRONLY);
if(wfd==-1)
{
perror("open error");
return -1;
}
//创建保存文件
int kfd=open("file1",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(kfd==-1)
{
perror("open file error");
return -1;
}
printf("管道文件写端打开\n");
char wbuf[128]="";
while(1)
{
printf("请输入>>>");
fgets(wbuf,sizeof(wbuf),stdin);
//写入保存文件
write(kfd,wbuf,strlen(wbuf));
wbuf[strlen(wbuf)-1]=0;
//写入管道
write(wfd,wbuf,strlen(wbuf));
if(strcmp(wbuf,"quit")==0)
{
break;
}
}
close(kfd);
close(wfd);
return 0;
}
recv.c
#include<myhead.h>
int main(int argc, char const *argv[])
{
//可读形式打开管道
int rfd=open("./linux",O_RDONLY);
if(rfd==-1)
{
perror("open error");
return -1;
}
printf("管道文件读端打开\n");
char rbuf[128]="";
while(1)
{
bzero(rbuf,sizeof(rbuf));
//读取管道
read(rfd,rbuf,sizeof(rbuf));
if(strcmp(rbuf,"quit")==0)
{
break;
}
printf("收到消息为:%s\n",rbuf);
}
close(rfd);
return 0;
}
creat.c
#include<myhead.h>
int main(int argc, char const *argv[])
{
//创建两个有名管道文件
if(mkfifo("pipe1",0664)==-1)
{
perror("mkfifo error");
return -1;
}
if(mkfifo("pipe2",0664)==-1)
{
perror("mkfifo error");
return -1;
}
getchar();
system("rm pipe1 pipe2");
return 0;
}
Aprocess.c
#include<myhead.h>
int main(int argc, char const *argv[])
{
//只写形式打开管道1
int Awfd=open("pipe1",O_WRONLY);
if(Awfd==-1)
{
perror("open pipe1 error");
return -1;
}
//只读形式打开管道2
int Brfd=open("pipe2",O_RDONLY);
if(Brfd==-1)
{
perror("open pipe2 error");
return -1;
}
//创建子进程
pid_t pid=fork();
if(pid<0)
{
perror("fork error");
return -1;
}
char buf[128]="";
//父进程发送
if(pid>0)
{
while(1)
{
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
write(Awfd,buf,strlen(buf));
if(strcmp(buf,"quit")==0)
{
break;
}
}
}
//子进程接受
else
{
while(1)
{
bzero(buf,sizeof(buf));
read(Brfd,buf,sizeof(buf));
if(strcmp(buf,"quit")==0)
{
break;
}
printf("B:%s\n",buf);
}
exit(EXIT_SUCCESS);
}
wait(NULL);
close(Awfd);
close(Brfd);
return 0;
}
Bprocess.c
#include<myhead.h>
int main(int argc, char const *argv[])
{
//只读形式打开管道1
int Arfd=open("pipe1",O_RDONLY);
if(Arfd==-1)
{
perror("open pipe1 error");
return -1;
}
//只写形式打开管道2
int Bwfd=open("pipe2",O_WRONLY);
if(Bwfd==-1)
{
perror("open pipe2 error");
return -1;
}
//创建子进程
pid_t pid=fork();
if(pid<0)
{
perror("fork error");
return -1;
}
char buf[128]="";
//子进程发送
if(pid==0)
{
while(1)
{
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
write(Bwfd,buf,strlen(buf));
if(strcmp(buf,"quit")==0)
{
break;
}
}
exit(EXIT_SUCCESS);
}
//父进程接受
else
{
while(1)
{
bzero(buf,sizeof(buf));
read(Arfd,buf,sizeof(buf));
if(strcmp(buf,"quit")==0)
{
break;
}
printf("A:%s\n",buf);
}
}
wait(NULL);
close(Bwfd);
close(Arfd);
return 0;
}