#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
if(argc<3){
printf("the number of argument should be at least 3\n");
printf("usage:./a.out sourceFileName destinationFileName\n");
return -1;
}
int sfd=-1;
int dfd=-1;
if((sfd=open(argv[1],O_RDONLY))==-1){
perror("open source file error");
return -1;
}
if((dfd=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0664))==-1){
perror("open destination file error");
return -1;
}
//calculate the size of source file
off_t srcFileSize=lseek(sfd,0,SEEK_END);
//char buf[20]="";
pid_t pid=-1;
/*--------------------------------the 1st child process*/
pid=fork();
if(pid==-1){
perror("fork error 1");
return -1;
}
if(pid==0){
//the 1st child process copy the first half of the source file
int res=-1;
int curPos=0;
char buf[10]="";
while(curPos<=srcFileSize/2){
lseek(sfd,curPos,SEEK_SET);
res=read(sfd,buf,sizeof(buf));
lseek(dfd,curPos,SEEK_SET);
write(dfd,buf,res);
curPos+=res;
}
printf("I am 1st child and my part copy is done!!!\n");
exit(EXIT_SUCCESS);
}
/*--------------------------------the 2nd child process*/
pid=fork();
if(pid==-1){
perror("fork error 2");
return -1;
}
if(pid==0){
//the 2nd child process copy the second half of the source file
int res=-1;
int curPos=srcFileSize/2+1;
char buf[10]="";
while(curPos<srcFileSize){
lseek(sfd,curPos,SEEK_SET);
res=read(sfd,buf,sizeof(buf));
lseek(dfd,curPos,SEEK_SET);
write(dfd,buf,res);
curPos+=res;
}
printf("I am 2nd child and my part copy is done!!!\n");
exit(EXIT_SUCCESS);
}
/*--------------------------------the parent process*/
printf("I am parent process and waiting for the copy finishing ...... \n");
wait(NULL);
wait(NULL);
close(dfd);
close(sfd);
printf("file copied succesfully!\n");
return 0;
}