作业1:有名管道,创建两个发送接收端,父进程写入管道1和管道2,子进程读取管道2和管道1.
创建两个有名管道文件:
#include <myhead.h>
int main(int argc, const char *argv[])
{
if((mkfifo("./fifo_1",0664)==-1)||((mkfifo("fifo_2",0664))==-1))
{
perror("mkfifo");
return -1;
}
//创建两个有名管道文件
return 0;
}
第一个子父进程:
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t id1;
id1=fork();
if(id1>0)//父进程1
{
int s1;
s1=open("fifo_1",O_WRONLY);
if(s1==-1)
{
perror("open s1");
return -1;
}
char buff[1024];
while(1)
{
int len=read(0,buff,sizeof(buff));//键盘输入
buff[strlen(buff)-1]='\0';//换行改为\0
write(s1,buff,len);//写入管道1
if(strcmp(buff,"quit")==0)
{
break;
}
}
close(s1);
}
else if(id1==0)//子进程1
{
int r2;
r2=open("fifo_2",O_RDONLY);
if(r2==-1)
{
perror("open r2");
return -1;
}
char buff[1024];
while(1)
{
int len=read(r2,buff,sizeof(buff));//读取管道文件2
write(1,buff,len);//输出到终端显示
/* if(strcmp(buff,"quit")==0)
{
break;
}*/
}
close(r2);
}
return 0;
}
第二个子父进程:
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t id2;
id2=fork();
if(id2>0)//父进程2
{
int s2;
s2=open("fifo_2",O_WRONLY);
if(s2==-1)
{
perror("open s2");
return -1;
}
char buff[1024];
while(1)
{
int len=read(0,buff,sizeof(buff));//键盘输入
buff[strlen(buff)-1]='\0';//换行改为\0
write(s2,buff,len);//写入管道2
if(strcmp(buff,"quit")==0)
{
break;
}
}
close(s2);
}
else if(id2==0)//子进程2
{
int r1;
r1=open("fifo_1",O_RDONLY);
if(r1==-1)
{
perror("open r1");
return -1;
}
char buff[1024];
while(1)
{
int len=read(r1,buff,sizeof(buff));//读取管道文件2
write(1,buff,len);//输出到终端显示
/* if(strcmp(buff,"quit")==0)
{
break;
}*/
}
close(r1);
}
return 0;
}