多进程拷贝--系统调用read和write函数实现
多进程拷贝再实现,本次使用系统函数 read()和write()函数来实现拷贝。
*************************************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
//执行命令:./应用名 源文件名 目标文件名 进程数量
int main(int argc,char *argv[])
{
if(argc != 4)
{
printf("Please input ./a.out <srcfile> <dstfile> <conut>\n");
exit(1);
}
int i;
int fds,fdd;
int n = atoi(argv[3]);
int blocksize;
struct stat sta;
pid_t pid;
fds = open(argv[1],O_RDONLY);
if(fds < 0)
{
perror("open src failed.");
exit(1);
}
fdd = open(argv[2],O_WRONLY|O_CREAT,0664);
if(fdd < 0)
{
perror("open dst failed.");
close(fds);
exit(1);
}
if(fstat(fds,&sta))
{
printf("Can't get src stat.\n");
close(fds);
close(fdd);
exit(1);
}
blocksize = sta.st_size/n;
ftruncate(fdd,sta.st_size);
for(i=0;i<n;i++)
{
pid = fork();
if(pid < 0)
{
printf("fork error\n");
close(fds);
close(fdd);
exit(1);
}
else if(0 == pid)
break;
}
if(i < n)
{
//In children
if((n-1) == i)
blocksize += sta.st_size%n;
char buf[blocksize];
int cn;
//将光标定位到要读/写的位置。
lseek(fds,blocksize*i,SEEK_SET);
lseek(fdd,blocksize*i,SEEK_SET);
cn = read(fds,buf,blocksize);
write(fdd,buf,cn);
printf("In %dth pid,copy done\n",i+1);
}
else
{
int j;
for(j=0;j<n;j++)
{
waitpid(-1,NULL,WNOHANG);
}
//In parent
close(fds);
close(fdd);
}
return 0;
}
*************************************************************************************
执行结果:

打开文件1.txt,可以到看文件被拷贝过来。

浙公网安备 33010602011771号