linux--多進程進行文件拷貝

學習IO的時候,咱們都曾經利用文件IO函數,標準IO函數都實現了對文件的拷貝,併發

對某一個文件進行拷貝時,咱們能夠考慮一下幾種方式:less

a.單進程拷貝:函數

假設某一文件須要拷貝100字節,每個時間片能夠完成拷貝20個字節工做量,則須要被分配5個時間片才能夠完成任務,但問題是這些個時間片並非被連續分配的,咱們並不知道學習

到通過多少時間片纔會有下一個能分配給該進程的時間片,爲了解決這個問題,咱們有了第二種方法。spa

b.多進程拷貝(單核單CPU):code

 經過切換進程,隨着進程數的增長,當前程序得到時間片所須要的時間也就更少。blog

c.多進程拷貝(多核併發處理)進程

咱們要實現的是第二個方法,代碼以下:get

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<unistd.h>
  4 #include<fcntl.h>
  5 #include<string.h>
  6 #include<sys/types.h>
  7 #include<sys/stat.h>
  8 #include<sys/wait.h>
  9 int cutting(char *src,int prono)
 10 {
 11     int fd,filesize;
 12     if((fd=open(src,O_RDONLY))==-1)
 13     {
 14         perror("cutting open failed");
 15     return -1;
 16     }
 17     if((filesize=lseek(fd,0,SEEK_END))==-1)
 18     {
 19         perror("filesize failed");
 20         close(fd);
 21         return -1;
 22     }
 23     int blocksize;
 24     if(filesize%prono==0)
 25     {
 26         blocksize=filesize/prono;
 27     }
 28     else
 29     {
 30         blocksize=filesize/prono+1;
 31     }
 32     close(fd);
 33     //printf("%d",blocksize);
 34     return blocksize;
 35 
 36 }
 37 int copy(char *src,char *des,int pos,int blocksize)
 38 {
 39     if(access(src,F_OK)==-1)
 40     {
 41         perror("acess failed");
 42     }
 43     int fd1,fd2;
 44     char buf[blocksize];
 45     fd1=open(src,O_RDONLY);
 46     fd2=open(des,O_WRONLY|O_CREAT,0664);
 47     lseek(fd1,pos,SEEK_SET);
 48     lseek(fd2,pos,SEEK_SET);
 49 
 50 
 51     int len=read(fd1,buf,sizeof(buf));
 52     write(fd2,buf,len);
 53     close(fd1);
 54     close(fd2);
 55     return 1;
 56 }
 57 int create(char *src,char *des,int blocksize,int prono)
 58 {
 59     int i;
 60     pid_t pid;
 61     int pos=0;
 62     for(i=0;i<prono;i++)
 63     {
 64         pid=fork();
 65         if(pid>0)
 66         {
 67             pos+=blocksize;
 68 
 69             //printf("當前讀取位置爲:%d,每次所讀文件大小:%d,當前進程爲%d\n",pos,blocksize,getpid());
 70            
 71     }
 72 
 73         else if(pid==0)
 74         {
 75             copy(src,des,pos,blocksize);
 76             
 77             printf("當前讀取位置爲:%d,每次所讀文件大小:%d,當前進程爲%d\n",pos,blocksize,getpid());
 78             break;
 79         }
 80         
 81     }
 82     return 1;
 83 }
 84 int main(int argc,char **argv)
 85 {
 86     int prono;
 87     int blocksize;
 88     if(argc<3)
 89     {
 90         printf("the canshu you have chuan are too less\n");
 91     }
 92     if(argv[3]!=0)
 93     {
 94         prono=atoi(argv[3]);
 95         if(prono<=0||prono>=100)
 96         {
 97             printf("the num of the process you give cant not less than 0 or more than 100\n");
 98         }
 99         
100     }
101     else prono=5;
102     blocksize=cutting (argv[1],prono);
103     create(argv[1],argv[2],blocksize,prono);
104 
105     return 0;
106 }

相關文章
相關標籤/搜索