程序寫的比較簡單,可能部分細節不是很完美,以後有需要可以再修改。
/*
*多進程拷貝
*/
#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-4*size/5;
else len = size/5;
sleep(i); //保證數據是按照原來的順序寫入的
strncpy(q+i*size/5,p+i*size/5,len);
printf("the %dth process write successfully\n",i+1);
munmap(p,size);
munmap(q,size);
return 0;
}
源文件內容:
程序執行後生成的目標文件內容: