Linux多进程文件拷贝(CC++)——方案一(不使用mmap内存映射)

    技术2022-07-10  128

    代码所用函数:open(),read(),write(),fstat(),lseek(),fork(),close();


    #include <iostream> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> using namespace std; int main(int argc,char* argv[]) {     if(argc < 4) {         cout << "Usage: ./a.out src des count_process" << endl;         return 0;     }     int srcfd = open(argv[1],O_RDONLY);     int desfd = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0664);     if(srcfd == -1 || desfd == -1) {         perror("open src or des error");         return -1;     }     struct stat statbuf;     int ret = fstat(srcfd,&statbuf);     if(ret == -1) {         perror("stat error");         return -1;     }     int fileSize = statbuf.st_size;     cout <<"fileSize = " <<fileSize<<endl;     int process_count = atoi(argv[3]);     int eachSize = fileSize/process_count;     cout <<"eachSize = " <<eachSize <<endl;     pid_t pid;     while(process_count--) {         pid = fork();         if(pid == -1) {             perror("fork error");             return -1;         } else if (pid == 0) {             break;         }                  }     //拷贝工作全部由子进程完成     if(pid == 0) {         cout <<"process_count = " <<process_count<<endl;         //设置每个子进程对文件操作的偏移量         if(lseek(srcfd,eachSize*process_count,SEEK_SET) == -1 ||            lseek(desfd,eachSize*process_count,SEEK_SET) == -1) {                 perror("lseek error");                 return -1;             }             char buf[1024];             int flag = 0;             int readsize;             do{                 readsize = read(srcfd,buf,sizeof(buf));                 write(desfd,buf,readsize);                 flag += readsize;                 //最后创建出来的子进程负责最后一个文件块(这个块一般情况下都大于eachSize)                 if(flag > eachSize && atoi(argv[3]) != process_count) {                     break;                 }             }while(readsize);     } else {         //回收一下子进程,此处就不回收了,由init进程代为回收         cout <<" i am parent" << endl;             }     if(close(srcfd) == -1 || close(desfd) == -1) {         perror("close error");         return -1;     }     return 0; }

    这种方式效率比较低,写文件时覆盖情况比较严重,欢迎指出代码问题。  

    Processed: 0.010, SQL: 9