之前写过一个多进程copy文件,是直接通过操作文件描述符来做的,链接如下https://blog.youkuaiyun.com/woshichaoren1/article/details/84800807
此次多线程copy文件是用mmap内存映射操作,读写速度要快一些。废话不多说直接上代码
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
struct param
{
int legth; //长度
int offset; //lseek位置
char src[255]; //源文件位置
char des[255]; //目的文件位置
};
void* copyContext(void *arg)
{
param *myparam = (param*)arg;
int fd_src = open(myparam->src,O_RDONLY);
int fd_des = open(myparam->des,O_RDWR);
char *s_addr = (char*)mmap(NULL,myparam->legth,PROT_READ,MAP_SHARED,fd_src,myparam->offset);
char *d_addr = (char*)mmap(NULL,myparam->legth,PROT_READ|PROT_WRITE,MAP_SHARED,fd_des,myparam->offset);
//copy
memcpy(d_addr,s_addr,myparam->legth);
return NULL;
}
int main(int argc,char *argv[])
{
if(argc <4)
{
printf("please input like this : copy srcfile, descfile , pthreadnum\n");
}
pthread_t *tid;
param *params;
params = (param *)malloc(atoi(argv[3])*sizeof(param));
tid = (pthread_t *)malloc(atoi(argv[3])*sizeof(pthread_t));
// params = new param[argc];
// tid = new pthread_t[argc];
int fd = open(argv[1],O_RDONLY);
if (fd<0)
{
perror("open src filed:");
exit(errno);
}
umask(000);
int fd2 = open(argv[2],O_RDWR|O_CREAT,0777);
if(fd2<0)
{
perror("open des filed:");
exit(errno);
}
int filesize = lseek(fd,0,SEEK_END);
//先初始化大小为一样
lseek(fd2,filesize-1,SEEK_SET);
write(fd2,"0",1);
//初始化变量
int offset = filesize/argc + (filesize%argc?0:1);
for (int i = 0; i <argc ; ++i) {
params[i].legth = filesize;
params[i].offset = i*offset;
strcpy(params[i].src ,argv[1]);
strcpy(params[i].des ,argv[2]);
}
//创建线程
for (int i = 0; i <atoi(argv[3]) ; ++i) {
pthread_create(&tid[i], NULL,copyContext,¶ms[i]);
}
//给子线程收尸
for (int j = 0; j < atoi(argv[3]); ++j) {
pthread_join(tid[j],NULL);
}
return 0;
}
之前因为没注意用的new来写的 new是c++的函数,一直报new的错。。。望注意⚠️
代码有一些细节没写。。比如cp后文件访问权限与源文件的不同,还有命令参数不符等错误没有抛出异常。。。。有兴趣的自己写下吧。如有错误望指出