作业1:有名管道,创建两个发送接收端,父进程写入管道1和管道2,子进程读取管道2和管道1.
右进程
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid=fork();
if(pid>0)//父进程,将数据发送至管道1
{
int fd1;
int len;
char buff[1024];
fd1=open("./fifo_a",O_WRONLY);
if(fd1==-1)
{
perror("打开管道1");
return -1;
}
while(1)
{
len=read(0,buff,sizeof(buff));//从键盘读取数据
buff[strlen(buff)-1] = '\0';
write(fd1,buff,len);//将数据发送至管道1
if(strcmp(buff,"quit")==0)
{
break;
}
}
close(fd1);
}
else if(pid==0)
{
int fd2;
int len1;
char buff1[1024];
fd2=open("./fifo_b",O_RDONLY);
if(fd2==-1)
{
perror("打开管道2");
return -1;
}
while(1)
{
len1=read(fd2,buff1,sizeof(buff1));//从管道2读取数据
write(1,buff1,len1);
if(strcmp(buff1,"quit")==0)
{
break;
}
}
close(fd2);
}
else
{
perror("pid");
return -1;
}
return 0;
}
左进程
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid=fork();
if(pid>0)//父进程,将数据发送至管道1
{
int fd1;
int len;
char buff[1024];
fd1=open("./fifo_b",O_WRONLY);
if(fd1==-1)
{
perror("打开管道1");
return -1;
}
while(1)
{
len=read(0,buff,sizeof(buff));//从键盘读取数据
buff[len-1] = '\0';
write(fd1,buff,len);//将数据发送至管道1
if(strcmp(buff,"quit")==0)
{
break;
}
}
close(fd1);
}
else if(pid==0)
{
int fd2;
int len1;
char buff1[1024];
fd2=open("./fifo_a",O_RDONLY);
if(fd2==-1)
{
perror("打开管道2");
return -1;
}
while(1)
{
len1=read(fd2,buff1,sizeof(buff1));//从管道2读取数据
write(1,buff1,len1);
if(strcmp(buff1,"quit")==0)
{
break;
}
}
close(fd2);
}
else
{
perror("pid");
return -1;
}
return 0;
}