#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100
int child_copy(int fd_src,int fd_dest)
{
char buf[MAXSIZE];
int n;
memset(buf,0,sizeof(buf));
lseek(fd_src,0,SEEK_SET);
lseek(fd_dest,0,SEEK_SET);
while((n = read(fd_src,buf,sizeof(buf))) > 0)
{
write(fd_dest,buf,n);
}
printf("THE SEEK_SET is :%ld \n",lseek(fd_src,0,SEEK_SET));
return 0;
}
int father_copy(int fd_src,int fd_dest,int len)
{
char buf[MAXSIZE];
int n;
memset(buf,0,sizeof(buf));
lseek(fd_src,len/2,SEEK_SET);
lseek(fd_dest,len/2,SEEK_SET);
while((n = read(fd_src,buf,sizeof(buf))) > 0){
write(fd_dest,buf,n);
printf("hello %d\n",len/2);
//printf("hello2 %ld\n",lseek(fd_src,len/2,SEEK_SET));
}
return 0;
}
int main(int argc,char *argv[])
{
pid_t pid;
int fd_src,fd_dest;
int len;
if(argc != 3)
{
fprintf(stdout,"usage:%s src dest\n",argv[0]);
return -1;
}
if((fd_src = open(argv[1],O_RDONLY)) < 0)
{
perror("fail to open:");
exit(-1);
}
if((fd_dest = open(argv[2],O_WRONLY | O_CREAT | O_TRUNC,0666)) < 0)
{
perror("fail to open:");
exit(-1);
}
len = lseek(fd_src,0,SEEK_END);
if(ftruncate(fd_dest,len) == -1)//会将参数FD_DEST指向的大小改为LEN指向的大小
//超过LEN的会被删掉
{
perror("ftruncate");
exit(-1);
}
if((pid = fork()) < 0){
perror("fail to fork:");
exit(-1);
}else if(pid ==0){
child_copy(fd_src,fd_dest);
printf("child copy is ok!\n");
close(fd_src);
close(fd_dest);
exit(0);
}else{
close(fd_src);
close(fd_dest);
if((fd_src = open(argv[1],O_RDONLY)) < 0){
perror("fail to open");
exit(-1);
}
if((fd_dest = open(argv[2],O_WRONLY)) < 0){
perror("fail to open");
exit(-1);
}
father_copy(fd_src,fd_dest,len);
close(fd_src);
close(fd_dest);
printf("father copy is ok!\n");
exit(0);
}
exit(0);
}