1. 程式人生 > >linux多執行緒實現檔案複製

linux多執行緒實現檔案複製

之前寫過一個多程序copy檔案,是直接通過操作檔案描述符來做的,連結如下https://blog.csdn.net/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,&params[i]);
    }

    //給子執行緒收屍
    for (int j = 0; j < atoi(argv[3]); ++j) {
        pthread_join(tid[j],NULL);
    }

    return 0;

}

之前因為沒注意用的new來寫的 new是c++的函式,一直報new的錯。。。望注意⚠️ 

程式碼有一些細節沒寫。。比如cp後文件訪問許可權與原始檔的不同,還有命令引數不符等錯誤沒有丟擲異常。。。。有興趣的自己寫下吧。如有錯誤望指出