利用普通管道设计一个文件复制程序filecopy,将要复制的文件内容写入管道,子进程将从管道中读出该文件,并将其写入目标文件
刚开始鄙人准备用有名管道fifo来进行操作,但发现进程等待实在是无法预测(就贼离谱)。然后就一直搁置(反正作业只要写一题)。看来不少大佬的提交,顿时福至心灵(怒从心头起,恶向胆边生),改用无名管道去做这一题,终于给调出来了。
话不多说。直接上代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZE 1024
#define Write_type 1
#define Read_type 0
void child_do(int fd[])
{
close(fd[Write_type]);
int fd_write = open("output.txt",O_RDWR | O_CREAT,0317);
if(fd_write == -1)
{
perror("open");
return;
}
int red;
char buf[SIZE] = {0};
while(red = read(fd[Read_type],buf,SIZE))
{
if(ret == -1)
{
perror("read");
return;
}
write(fd_write,buf,red);
}
printf("File copy successed\n");
close(fd[Read_type]);
close(fd_write);
}
void father_do(int fd[])
{
close (fd[Read_type]);
int fd_read = open("input.txt",O_RDONLY ,0317);
if(fd_read == -1)
{
perror("open");
return;
}
int red;
char buf[SIZE] = {0};
while(red = read(fd_read,buf,SIZE))
{
if (red == -1)
{
perror ("read");
break;
}
write(fd[Write_type],buf,red);
}
close (fd[Write_type]);
close (fd_read);
}
int main ()
{
int fd[2];
int red = pipe(fd);
if(red == -1) //管道加载失败
{
perror("pipe");
return -1;
}
pid_t pid = fork();
switch(pid)
{
case -1: //进程申请失败
{
perror("fork");
break;
}
case 0: //进行子进程
{
child_do(fd);
break;
}
default: //进行父进程
{
father_do(fd);
break;
}
}
return 0;
}
运行结果:
还有就是之前用fifo写的代码,大家也可以参考以下:
写入文件:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
using namespace std;
int main()
{
mkfifo("guandao",0317);
int infd1=open("file",O_RDONLY);
if (infd1==-1)
{
cout<<"open error !"<<endl;
return -1;
}
int outfd1 =open("file",O_WRONLY);
if (outfd1==-1)
{
cout<<"open error !"<<endl;
return -1;
}
int num1;
char buf[1000];
while ((num1=read(infd1,buf,1000))>0)
write (outfd1,buf,num1);
close (infd1);
close(outfd1);
return 0;
}
读出文件并复制:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
using namespace std;
int main()
{
int outfd2=open("./filecopy",O_WRONLY|O_CREAT|O_TRUNC,0317);
if(outfd2==-1)
{
cout<<"open error!"<<endl;
return -1;
}
int infd2=open("guandao",O_RDONLY);
if (infd2==-1)
{
cout<<"open error!"<<endl;
return -1;
}
int num2;
char buf[1000];
while ((num2=read(infd2,buf,1000))>0)
write(outfd2,buf,num2);
close(infd2);
close(outfd2);
unlink("guangdao");
return 0;
}
结果就是没有结果。。。。 很迷。。。
0 条评论