正在加载……
专注、离线、切勿分心
#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/mman.h>
#include<string.h>
#include<strings.h>
#define MAXFILESIZE 128
#define MAXTHERAD 10
static int file_size;
static int new_file_size;  //其实只用设置前面一个就好了,这里是开始写这段代码拿来测试文件空洞有没有形成
static char *file_point;
static char *new_file_point;
static int threadNum = 0;
//这些静态变量不赋初值默认都是0
void *pthFunc(void *args)
{
        int i = threadNum++;
        int srcpoint = (file_size/10)*i;   //获取对应线程的拷贝起始点
        int destpoint = srcpoint;
        if(i!=9)
        {
                memcpy(new_file_point+destpoint,file_point+srcpoint,file_size/10);
        }
        else
        { //考虑最后一个线程拷贝的可能不足一块
                memcpy(new_file_point+destpoint,file_point+srcpoint,file_size-srcpoint);
        }
        pthread_exit(NULL);
}


int main(int argc,char **argv)
{
        if(2!=argc)
        {
                printf("error args\n");
                return -1;
        }
        int fdr = open(argv[1],O_RDONLY,0666);
        if(-1==fdr)
        {
                printf("fdr open error\n");
                return -1;
        }
        char new_file_name[MAXFILESIZE];
        sprintf(new_file_name,"%s%s","new_",argv[1]);
        int fdw = open(new_file_name,O_CREAT|O_RDWR,0666);
        if(-1==fdw)
        {
                printf("fdw open error\n");
                return -1;
        }
        struct stat buf1,buf2;
        bzero(&buf1,sizeof(buf1));
        bzero(&buf2,sizeof(buf2));
        fstat(fdr,&buf1);
        file_size = buf1.st_size;
        ftruncate(fdw,file_size);
        fstat(fdw,&buf2);
        new_file_size = buf2.st_size;
        file_point = (char*)mmap(NULL,file_size,PROT_READ,MAP_SHARED,fdr,0);  
//prot只是读权限,则文件描述符要有可读权限
        new_file_point = (char*)mmap(NULL,new_file_size,PROT_WRITE,MAP_SHARED,fdw,0); //prot是写权限,则文件描述符要有可读可写权限
        pthread_t pth[MAXTHERAD];
        for(int i = 0;i<10;i++)
        {
                pthread_create(&pth[i],NULL,pthFunc,NULL);
        }
        printf("start copying\n");
        for(int i = 0;i<10;i++)
        {
                pthread_join(pth[i],NULL);
        }
        printf("Done!\n");  //没有解除映射,不过进程结束自动解除
        return 0;
}


posted on 2018-03-10 12:05  正在加载……  阅读(1338)  评论(0编辑  收藏  举报