作业:管道文件实现两个文件内容的读与写
文件一:
#include<myhead.h>
int main(int argc, const char *argv[])
{
//创建有名管道1
if(mkfifo("./myfifo", 0664) != 0)
{
perror("mkfifo error");
return -1;
}
printf("管道创建成功\n");
//打开管道文件1
int fd1 = -1;
if((fd1 = open("./myfifo", O_WRONLY)) == -1)
{
perror("open error");
return -1;
}
//打开管道文件2
int fd2 = -1;
if((fd2 = open("./secondfifo", O_RDONLY)) == -1)
{
perror("open error");
return -1;
}
//创建父子进程
pid_t pid=-1;
pid = fork();
if(pid>0)
{
char wbuf[128] ="";
while(1)
{
printf("请输入>>");
fgets(wbuf, sizeof(wbuf), stdin);
wbuf[strlen(wbuf)-1] = '\0';
//将数据写入到管道中
write(fd1, wbuf, strlen(wbuf));
if(strcmp(wbuf, "quit") == 0)
{
break;
}
}
wait(NULL);
exit(0);
}else if(pid==0){
char rbuf[128] ="";
while(1)
{
bzero(rbuf, sizeof(rbuf));
//从管道文件中读取数据
read(fd2, rbuf, sizeof(rbuf));
printf("读取的数据为:%s\n", rbuf);
if(strcmp(rbuf, "quit") == 0)
{
break;
}
}
exit(0);
}else{
perror("fork error");
return -1;
}
//关闭文件描述符
close(fd1);
close(fd2);
return 0;
}
文件二
#include<myhead.h>
int main(int argc, const char *argv[])
{
//创建有名管道2
if(mkfifo("./secondfifo",0664)!=0)
{
perror("mkfifo error");
return -1;
}
printf("管道创建成功\n");
//打开管道文件1
int fd1 = -1;
if((fd1 = open("./myfifo", O_RDONLY)) == -1)
{
perror("open error");
return -1;
}
//打开管道文件2
int fd2 = -1;
if((fd2 = open("./secondfifo", O_WRONLY)) == -1)
{
perror("open error");
return -1;
}
//创建父子进程
pid_t pid=-1;
pid = fork();
if(pid>0)
{
char rbuf[128] ="";
while(1)
{
bzero(rbuf, sizeof(rbuf));
//从管道文件中读取数据
read(fd1, rbuf, sizeof(rbuf));
printf("读取的数据为:%s\n", rbuf);
if(strcmp(rbuf, "quit") == 0)
{
break;
}
}
wait(NULL);
exit(0);
}else if(pid==0)
{
char wbuf[128] ="";
while(1)
{
printf("请输入>>");
fgets(wbuf, sizeof(wbuf), stdin);
wbuf[strlen(wbuf)-1] = '\0';
//将数据写入到管道中
write(fd2, wbuf, strlen(wbuf));
if(strcmp(wbuf, "quit") == 0)
{
break;
}
}
exit(0);
}else{
perror("fork error");
return -1;
}
//关闭文件描述符
close(fd1);
close(fd2);
return 0;
}
输出结果: