程序写的比较简单,可能部分细节不是很完美,以后有需要可以再修改。
/*
*多进程拷贝
*/
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/mman.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
int main()
{
pid_t pid;
int i;
int size;
int fd1,fd2;
char *p,*q;
struct stat statbuff;
/* 获取目标文件的大小 */
if(stat("./source.txt",&statbuff)<0){
perror("stat error");
exit(1);
}
size = statbuff.st_size;
printf("size = %d\n",size);
/* 打开文件*/
fd1 = open("./source.txt",O_RDONLY);
fd2 = open("./target.txt",O_RDWR|O_CREAT|O_TRUNC,0644);
ftruncate(fd2,size); //设定目标文件的大小
if(fd2 == -1|fd1 == -1){
perror("open error");
exit(1);
}
/*创建映射*/
p = mmap(NULL,size,PROT_READ,MAP_SHARED,fd1,0);
q = mmap(NULL,size,PROT_WRITE|PROT_READ,MAP_SHARED,fd2,0);
if(p == MAP_FAILED|q == MAP_FAILED){
perror("mmap error");
exit(1);
}
/*创建子进程*/
for(i=0;i<4;i++){
pid = fork();
if(pid < 0){
perror("fork error");
exit(1);
}
if(pid == 0) break;
}
/*求出每个进程需要写入的长度*/
int len;
if(i == 4) len = size-size/5*4;
else len = size/5;
sleep(i); //保证数据是按照原来的顺序写入的
strncpy(q+size/5*i,p+size/5*i,len);
printf("the %dth process write successfully\n",i+1);
munmap(p,size);
munmap(q,size);
return 0;
}
源文件内容:
程序执行后生成的目标文件内容: