学习了mmap以后,实现一个简单的小程序,进行多个进程对一个文件进行拷贝。
Linux mmap共享内存学习可以参考我的另一篇博客:传送门
实现思想
我们可以将原来的文件利用mmap分成多个段分别进行传输。
实现代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/mman.h>
#include<fcntl.h>
int main(int argc,char *argv[])
{
char *input,*output;
if(argc<2)
{
printf("You should input file name\n");
exit(1);
}
else if(argc>3)
{
printf("too many arguments\n");
exit(1);
}
else if(3 == argc)
{
input=argv[1];
output=argv[2];
}
else if(2 == argc)
{
input=argv[1];
output=strcat(input,".out");
}
int fd1 = open(input,O_RDONLY);
if(-1 == fd1)
{
perror("input file open error:");
exit(1);
}
int fd2 = open(output,O_RDWR | O_CREAT | O_TRUNC,0644);
if(-1 == fd2)
{
perror("output file open error:");
exit(1);
}
int file_size = lseek(fd1,0,SEEK_END);
int ret = ftruncate(fd2,file_size);
if(-1 == ret)
{
perror("ftruncate ouput file error:");
exit(1);
}
input = mmap(NULL, file_size, PROT_READ, MAP_SHARED, fd1, 0);
if(MAP_FAILED == input)
{
perror("input mmap error:");
exit(1);
}
close(fd1);
output = mmap(NULL, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd2, 0);
if(MAP_FAILED == output)
{
perror("output mmap error:");
exit(1);
}
close(fd2);
int psize = file_size / 4;
pid_t pid;
for(int son=0; son<4; ++son)
{
pid = fork();
if(-1 == pid)
{
perror("fork error:");
exit(1);
}
else if(0 == pid)
{
memcpy(output+son*psize, input+son*psize, psize);
exit(0);
}
}
if(file_size > psize * 4)
{
memcpy(output+4*psize,input+4*psize,file_size-psize*4);
}
ret = munmap(input, file_size);
if(-1 == ret)
{
perror("close input mmap error:");
exit(1);
}
ret = munmap(output, file_size);
if(-1 == ret)
{
perror("close output mmap error:");
exit(1);
}
return 0;
}