LINUX 实现文件多进程拷贝

题目:在linux下运用5个进程拷贝一个大文件

#include<stdio.h>
 #include<stdlib.h> 
#include<sys/types.h>
#include<dirent.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/mman.h>
#include<sys/wait.h>

int main(){
    char * mem;
    int fd1,fd2;
    struct stat buf; 
    int status;
    fd1=open("cccc.txt",O_RDWR|O_CREAT,0644);//打开文件1,写出文件
fstat(fd1, &buf);
    fd2=open("text2.txt",O_RDWR|O_CREAT|O_TRUNC|O_APPEND,0644);//打开文件2,写入文件
    if(fd1<0){
        perror("open error\n");
    exit(1);
    }   
    if(fd2<0){
        perror("open txt2  error\n");
        exit(1);
    }   
    mem=mmap(NULL,buf.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd1,0);  //建立映射区

    if(mem==MAP_FAILED){
        perror(" mem error \n");
        exit(1);
    }   
    pid_t pid;
    int i;
    for(i=0;i<5;i++){       //建立5个子进程
    pid =fork();
    if(pid==-1){
        perror("error\n");
        exit(1);
    }else if(pid==0&&i<4){         //前4个拷贝文件大小的1/5,pid==0是子进程
        int count=read(fd1,mem+(i*1048576),1048576);
        if(count==-1){
            perror("read error\n");
            exit(1);
        }   
        int ret=write(fd2,mem+(i*1048576),count);
        if(ret==-1){
          perror("write error\n");
        exit(1);
        }   
    printf("the %d part copy has complished\n",i+1);
    }else if(pid==0&&i==4){  ///最后一个拷贝剩下的
                 int count=read(fd1,mem+(i*1048576),buf.st_size-(i*1048576));
                           if(count==-1){
                              perror("read error\n");
                                        exit(1);                            } 
                             int ret=write(fd2,mem+(i*1048576),count);
                                             if(ret==-1){
                              perror("write error\n");
                              exit(1);
}
                              printf("the %d part copy has complished\n",i+1);
    } else  {  //父进程break
        break;
    sleep(10);
   //   pid=fork();
//int   wpid=wait(&status);
//  printf("the %d part copy has complished\n",i+1);
    }
    }
    close(fd1);
    close(fd2);
}
 --                                                                                                              
发布了8 篇原创文章 · 获赞 0 · 访问量 1213

猜你喜欢

转载自blog.csdn.net/qq_42695315/article/details/102675457