#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <memory.h>
#include <sys/wait.h>
#include <pthread.h>
#include <stdlib.h>
int file_size(char* filename)
{
struct stat statbuf;
stat(filename, &statbuf);
int size = statbuf.st_size;
return size;
}
int size = 0;
int each_size = 0;
int last_size = 0;
char* s_ptr;
char* o_ptr;
void* pthread_copy(void* arg)
{
int i = (int)arg;
if (i == 4)
{
sleep(i);
memcpy(o_ptr + i * each_size, s_ptr + i * each_size, each_size);
}
else
{
sleep(i);
memcpy(o_ptr + i * each_size, s_ptr + i * each_size, each_size);
}
pthread_exit((void*)1);
}
int main(int argc, char* argv[])
{
//参数一:要拷贝的文件路径名
if (argv[1] == "")
{
printf("参数不能为空");
exit(1);
}
//参数二:目标文件路径名
if (argv[2] == "")
{
printf("参数不能为空");
exit(1);
}
int n = 5;//创建子进程的个数
int s_ret = 0, o_ret = 0;
int i = 0;
//打开源文件,只读模式
s_ret = open(argv[1], O_RDONLY);
if (s_ret == -1)
{
perror("file error:");
exit(1);
}
//目标模式,没有则创建,只写模式
o_ret = open(argv[2], O_CREAT | O_RDWR, 0644);
if (o_ret == -1)
{
perror("file error:");
exit(1);
}
//获取文件大小
size = file_size(argv[1]);
//printf("file size: %d \n",size);
//扩展目标文件
ftruncate(o_ret, size);
//内存映射
s_ptr = (char*)mmap(NULL, size, PROT_READ, MAP_PRIVATE, s_ret, 0);
o_ptr = (char*)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, o_ret, 0);
if (o_ptr == MAP_FAILED)
{
perror("s_ptr mmap error:");
exit(1);
}
//关闭文件描述符
close(s_ret);
close(o_ret);
//实现拷贝
each_size = size / n;
last_size = size - (n * each_size);
pid_t pid;
pthread_t tid;
//循环创建子线程
for (i = 0; i < n; i++)
{
int ret=pthread_create(&tid,NULL, pthread_copy,(void*)i);
if (ret != 0)
{
fprintf(stderr, "pthread_create error :%s\n", strerror(ret));
exit(1);
}
ret = pthread_join(tid, NULL);
if (ret != 0)
{
fprintf(stderr, "pthread_join error :%s\n", strerror(ret));
exit(1);
}
}
//释放映射空间
munmap(s_ptr, size);
munmap(o_ptr, size);
return 0;
}
结果: