今天对linux下mmap函数有了个新的认识
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
void error(char* str)
{
perror(str);
exit(-1);
}
int fd,fd1;
const int N=10;
int main(int argc,char *argv[])
{
int i,j;
int flage=10;
int *status;
pid_t pid,pid1;
if(argc < 2)
{
printf("输入文件错误,请检查参数!");
exit(-1);
}
fd = open(argv[1],O_RDWR);
if(fd==-1)
{
error("打开fd错误");
}
int ret = lseek(fd,0,SEEK_END);
fd1 = open("target",O_RDWR|O_CREAT,0664);
if(fd1==-1)
{
error("打开fd1错误");
}
ftruncate(fd1,ret);
char * map;
map = mmap(NULL,ret,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(map==MAP_FAILED)
{
error("读文件映射失败");
}
close(fd);
char *map1;
map1 = mmap(NULL,ret,PROT_READ|PROT_WRITE,MAP_SHARED,fd1,0);
if(map1==MAP_FAILED)
{
error("写文件映射失败");
}
close(fd1);
if(ret>10)
{
int rem = ret%N;
int avg = (ret-rem)/N;
for(i=0;i<N;i++)
{
pid = fork();
if(pid==0)
{
break;
}
}
if(i<N-1)
{
char *a=map1+i*avg;
char *b=map+i*avg;
memcpy(a,b,avg);
}
if(i==N-1)
{
char *c=map1+i*avg;
char *d=map+i*avg;
memcpy(c,d,avg+rem);
}
if(i==N)
{
do
{
pid1 = waitpid(-1,status,WNOHANG);
flage--;
}while(flage>0);
int aa = munmap(map,ret);
int bb = munmap(map1,ret);
return 0;
}
}
else
{
memcpy(map1,map,ret);
int aa = munmap(map,ret);
int bb = munmap(map1,ret);
return 0;
}
}