Chinaunix首页 | 论坛 | 博客
  • 博客访问: 237806
  • 博文数量: 35
  • 博客积分: 791
  • 博客等级: 军士长
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2012-09-05 16:56
文章分类
文章存档

2013年(7)

2012年(28)

我的朋友

分类: 嵌入式

2012-10-04 11:00:57

程序要求:
通过fork创建进程,子进程实现文件前半部分的拷贝,父进程实现文件后半部分的拷贝。

程序如下:

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <string.h>


  7. int child_copy(int fd_dest,int fd_src,int len)
  8. {
  9.     char buf[100];
  10.     int n = 0,count = 0;

  11.     memset(buf,0,sizeof(buf));

  12.     lseek(fd_src,0,SEEK_SET);
  13.     lseek(fd_dest,0,SEEK_SET);

  14.     while((n = read(fd_src,buf,sizeof(buf))) > 0){
  15.         write(fd_dest,buf,n);
  16.         count += n;

  17.         if(count > len / 2)
  18.             break;
  19.     }

  20.     return 0;
  21. }

  22. int father_copy(int fd_dest,int fd_src)
  23. {
  24.     char buf[100];
  25.     int n = 0,count = 0;

  26.     memset(buf,0,sizeof(buf));

  27.     while((n = read(fd_src,buf,sizeof(buf))) > 0){
  28.         write(fd_dest,buf,n);
  29.     }

  30.     return 0;

  31. }

  32. int main(int argc,char *argv[])
  33. {
  34.     int fd_src,fd_dest;
  35.     pid_t pid;
  36.     int len;
  37.     
  38.     if(argc < 3){
  39.         fprintf(stderr,"usage:%s srcfile destfile \n",argv[0]);
  40.         exit(-1);
  41.     }

  42.     if((fd_src = open(argv[1],O_RDONLY)) < 0){
  43.         perror("fail to open");
  44.         exit(-1);
  45.     }

  46.     if((fd_dest = open(argv[2],O_WRONLY | O_CREAT | O_TRUNC,0666)) < 0)
  47.     {
  48.         perror("fail to open");
  49.         exit(-1);
  50.     }

  51.     len = lseek(fd_src,0,SEEK_END);

  52.     if(ftruncate(fd_dest,len) < 0){
  53.         perror("fail to change size");
  54.         exit(-1);
  55.     }

  56.     if((pid = fork()) < 0){
  57.         perror("fail to open");
  58.         exit(-1);
  59.     }else if(pid == 0){
  60.         child_copy(fd_dest,fd_src,len);
  61.         close(fd_dest);
  62.         close(fd_src);
  63.         exit(0);
  64.     }else{
  65.         close(fd_dest);
  66.         close(fd_src);
  67.         
  68.         if((fd_src = open(argv[1],O_RDONLY)) < 0){
  69.             perror("fail to open");
  70.             exit(-1);
  71.         }

  72.         printf("fd_src : %d\n",fd_src);

  73.         if((fd_dest = open(argv[2],O_WRONLY)) < 0)
  74.         {
  75.             perror("fail to open");
  76.             exit(-1);
  77.         }

  78.         lseek(fd_src,len / 2,SEEK_SET);
  79.         lseek(fd_dest,len / 2,SEEK_SET);
  80.         
  81.         father_copy(fd_dest,fd_src);
  82.         
  83.         close(fd_dest);
  84.         close(fd_src);

  85.         exit(0);
  86.     }
  87.     
  88.     return 0;
  89. }


阅读(1333) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~