When learning Io, we have used the file IO function, the standard IO function has implemented a copy of the file,
When copying a file, we can consider several ways:
A. Single Process copy:
Assuming that a file requires a copy of 100 bytes, each time slice can be copied 20 bytes of work, you need to be allocated 5 time slices to complete the task, but the problem is that these time slices are not continuously allocated, we do not know
We have a second way to solve this problem by how much time it takes for the next time slice to be allocated to the process.
B. Multi-process copy (single core single CPU):
By switching processes, as the number of processes increases, it takes less time for the current program to get time slices.
C. Multi-process copy (multi-core concurrency processing)
We are going to implement the second method, the code is as follows:
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 intCutting (Char*SRC,intProno)Ten { One intfd,filesize; A if((Fd=open (src,o_rdonly)) ==-1) - { -Perror ("Cutting Open failed"); the return-1; - } - if(Filesize=lseek (FD,0, seek_end)) ==-1) - { +Perror ("FileSize failed"); - Close (FD); + return-1; A } at intblocksize; - if(filesize%prono==0) - { -blocksize=filesize/Prono; - } - Else in { -blocksize=filesize/prono+1; to } + Close (FD); - //printf ("%d", blocksize); the returnblocksize; * $ }Panax Notoginseng intCopyChar*SRC,Char*des,intPosintblocksize) - { the if(Access (SRC,F_OK) ==-1) + { APerror ("Acess failed"); the } + intfd1,fd2; - CharBuf[blocksize]; $fd1=open (src,o_rdonly); $Fd2=open (des,o_wronly| O_creat,0664); - Lseek (fd1,pos,seek_set); - Lseek (fd2,pos,seek_set); the - Wuyi intLen=read (Fd1,buf,sizeof(BUF)); the write (Fd2,buf,len); - Close (FD1); Wu Close (FD2); - return 1; About } $ intCreateChar*SRC,Char*des,intBlockSizeintProno) - { - inti; - pid_t pid; A intpos=0; + for(i=0; i<prono;i++) the { -Pid=fork (); $ if(pid>0) the { thepos+=blocksize; the the //printf ("The current read location is:%d, each time the file size is read:%d, the current process is%d\n", pos,blocksize,getpid ()); - in } the the Else if(pid==0) About { the copy (src,des,pos,blocksize); the theprintf"The current read location is:%d, each time the file size is read:%d, the current process is%d\n", Pos,blocksize,getpid ()); + Break; - } the Bayi } the return 1; the } - intMainintargcChar**argv) - { the intProno; the intblocksize; the if(argc<3) the { -printf"The Canshu you have Chuan is too less\n"); the } the if(argv[3]!=0) the {94Prono=atoi (argv[3]); the if(prono<=0|| prono>= -) the { theprintf"The num of the process you give cant isn't less than 0 or more than 100\n");98 } About - }101 Elseprono=5;102Blocksize=cutting (argv[1],prono);103Create (argv[1],argv[2],blocksize,prono);104 the return 0;106}
linux--multiple processes for file copies