利用子进程拷贝文件的前半部分,副进程拷贝后半部分C代码

#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);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值