#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
/*多进程拷贝文件*/
void sys_err(char* str)
{
perror(str);
exit(-1);
}
int main()
{
pid_t pid;
/*创建一个文件映射区*/
//1.打开一个文件
int fd;
fd = open("bigdata.txt",O_RDWR|O_CREAT, 0644);
if (fd == -1)
{
sys_err("open error\n");
}
//2.文件大小
struct stat statbuf;
stat("bigdata.txt", &statbuf);
int size = statbuf.st_size;
//3.mmap
int* p;
p = (int*)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(p==MAP_FAILED)
sys_err("mmap error\n");
//5个进程负责拷贝的大小
int unit_size = size / 5;
int copy_size[5];
for (int i = 0; i < 5; i++)
copy_size[i] = unit_size;
copy_size[4] = size - unit_size * 4;
/*循环创建5个进程*/
int* p_save = p;
for (int j = 0; j < 5; j++)
{
pid = fork();
if (pid > 0)
{
fd = open("bigdata_copy.txt", O_CREAT|O_RDWR|O_APPEND, 0644);
write(fd, p, copy_size[j]);
p_save += copy_size[j];
p = p_save;
}
else if(pid==0)
break;
else if (pid < 0)
sys_err("fork error\n");
}
printf("size:%d\n", size);
munmap(p, size);
return 0;
}
/*多进程拷贝文件*/