学习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 }