有名管道,创建两个发送接收端,父进程写入管道1和管道2,子进程读取管道2和管道1.
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid;
pid=fork();
if(pid>0)
{
int fd1;
fd1=open("./my_fifo1",O_WRONLY);
if(fd1==-1)
{
perror("open");
return -1;
}
char a[1024];
while(1)
{
int len=read(0,a,sizeof(a)-1);
a[len]='\0';
write(fd1,a,len);
if(strcmp(a,"quit\n")==0)
{
break;
}
}
close(fd1);
exit(EXIT_SUCCESS);
}
else if(pid==0)
{
int fd2;
//int fd3;
fd2=open("./my_fifo2",O_RDONLY);
if(fd2==-1)
{
perror("open");
return -1;
}
/*fd3=open("8.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd3==-1)
{
perror("open")
return -1;
}*/
char b[1024];
while(1)
{
int len=read(fd2,b,sizeof(b)-1);
b[len]='\0';
write(1,b,len);
if(strcmp(b,"quit\n")==0)
{
break;
}
}
close(fd2);
//close(fd3);
exit(EXIT_SUCCESS);
}
else
{
perror("fork");
return -1;
}
return 0;
}
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid;
pid=fork();
if(pid>0)
{
int fd1;
fd1=open("./my_fifo2",O_WRONLY);
if(fd1==-1)
{
perror("open");
return -1;
}
char a[1024];
while(1)
{
int len=read(0,a,sizeof(a)-1);
a[len]='\0';
write(fd1,a,len);
if(strcmp(a,"quit\n")==0)
{
break;
}
}
close(fd1);
exit(EXIT_SUCCESS);
}
else if(pid==0)
{
int fd2;
//int fd3;
fd2=open("./my_fifo1",O_RDONLY);
if(fd2==-1)
{
perror("open\n");
return -1;
}
/*fd3=open("9.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd3==-1)
{
perror("open");
return -1;
}*/
char b[1024];
while(1)
{
int len=read(fd2,b,sizeof(b)-1);
b[len]='\0';
write(1,b,len);
if(strcmp(b,"quit")==0)
{
break;
}
}
close(fd2);
//close(fd3);
exit(EXIT_SUCCESS);
}
else
{
perror("fork");
return -1;
exit(EXIT_FAILURE);
}
return 0;
}