多进程拷贝:实现将文件内容拷贝给另一个文件
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#define BUF_SIZE 400
int main(int argc, char *argv[])
{
int fd1, fd2, ret, len, i, n;
char *src = NULL;
char *dest = NULL;
pid_t pid;
printf("Current file path:%s\n", argv[0]);
fd1 = open(argv[1], O_RDWR);
if(fd1 == -1)
{
perror("open mmap.txt error:");
exit(1);
}
printf("mmap文件打开成功\n");
len = lseek(fd1, 0, SEEK_END);
printf("len = %d\n", len);
//将文件分为n个部分,创建n个子进程
if(len % BUF_SIZE == 0)//为BUF_SIZE的整数倍
{
n = len / BUF_SIZE;
printf("n = %d\n", n);
}
else//不是BUF_SIZE的整数倍,加一个子进程
{
n = len / BUF_SIZE + 1;
printf("n = %d\n", n);
}
lseek(fd1, 0, SEEK_SET);
src = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd1, 0);
if(src == MAP_FAILED)
{
perror("mmap mmap.txt error:");
exit(1);
}
printf("src mmap映射区创建成功\n");
//创建完共享内存后既可以关闭文件描述符
close(fd1);
fd2 = open(argv[2], O_RDWR|O_CREAT, 0664);
if(fd2 == -1)
{
perror("open copy.txt error:");
exit(1);
}
printf("copy文件打开成功\n");
//为目标文件拓展上面返回的文件描述符指向文件的大小
ret = ftruncate(fd2, len);
if(ret == -1)
{
perror("ftruncate error:");
exit(1);
}
dest = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd2, 0);
if(dest == MAP_FAILED)
{
perror("mmap copy.txt error:");
exit(1);
}
printf("dest mmap映射区创建成功\n");
//创建完共享内存后既可以关闭文件描述符
close(fd2);
for(i = 0; i < n; i++)
{
pid = fork();
if(pid < 0)
{
perror("fork error:");
exit(1);
}
else if(pid == 0)
{
break;
}
}
if(i < n)
{
//sleep(i);
//printf("I'm %dth child, I'm copying...\n", getpid());
//从第 i 个字符开始复制,连续复制 BUF_SIZE 个字符
if(i == (n - 1))
{
memcpy(dest + i*BUF_SIZE,src + i*BUF_SIZE, (len - i*BUF_SIZE));
//printf("Last child %d process print data:%s\n", getpid(), dest);
printf("Last i's length:%d\n", (len - i*BUF_SIZE));
}
else
{
memcpy(dest + i*BUF_SIZE,src + i*BUF_SIZE, BUF_SIZE);
//printf("Child %d process print data:%s\n", getpid(), dest);
}
}
else
{
//sleep(i);
wait(NULL);
printf("拷贝结束!\n");
ret = munmap(src, len);
if(ret == -1){
perror("munmap src error:");
exit(1);
}
ret = munmap(dest, len);
if(ret == -1){
perror("munmap dest error:");
exit(1);
}
}
return 0;
}
来源:CSDN
作者:allan-xy
链接:https://blog.csdn.net/tiandaochouqingong/article/details/103808990