多进程拷贝数据
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int mmap_mamcpy(char **argv)
{
int fp=open(argv[1],O_RDONLY);
if(fp<0)
{
printf("文件打开失败\n");
return 0;
}
int new_fp=open(argv[2],O_RDWR|O_CREAT,0666);
if(new_fp<0)
{
printf("新文件打开失败\n");
return 0;
}
//计算文件大小
struct stat buf;
fstat(fp,&buf);
if (buf.st_size<=0) return 0;
//设置新文件大小
ftruncate(new_fp,buf.st_size);
//文件映射
unsigned char *str_fp=mmap(NULL,buf.st_size,PROT_READ,MAP_SHARED,fp,0);
close(fp);
if(str_fp==(void *)-1)
{
printf("文件映射失败\n");
return 0;
}
//文件映射
unsigned char *str_new_fp=mmap(NULL,buf.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,new_fp,0);
close(new_fp);
if(str_new_fp==(void *)-1)
{
printf("新文件映射失败\n");
return 0;
}
int size=buf.st_size/5; //平均分配每个子进程拷贝的大小
int father_size=buf.st_size%5;
int i=0;
for(i=0;i<5;i++)
{
if(fork()==0) break;;
}
if (i<5)
{
memcpy(str_new_fp+i*size,str_fp+i*size,size);
}
else
{
if(father_size>0)
{
memcpy(str_new_fp+i*size,str_fp+i*size,size);
}
pid_t pid;
while(1)
{
pid=wait(NULL);
if(pid<0)
break;
printf("%d子进程拷贝成功\n",pid);
}
munmap(str_new_fp,buf.st_size);
munmap(str_fp,buf.st_size);
}
}
int main(int argc, char **argv)
{
if(argc!=3)
{
printf("请输入<.\a.out> [文件1] [文件2]\n");
return 0;
}
mmap_mamcpy(argv);
return 0;
}
标签:fp,数据文件,pid,argv,进程,拷贝,include,size
From: https://www.cnblogs.com/yesiming/p/18035650