思维导图
创建出三个进程完成两个文件之间拷贝工作,子进程1拷贝前一半内容,子进程2拷贝后一半内容,父进程回收子进程的资源
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <myhead.h>
int main(int argc, const char *argv[])
{//判断外部传参if(argc != 3){perror("error");return -1;}//定义文件指针FILE * fp = NULL;FILE * fq = NULL;//以只读if((fp=fopen(argv[1], "r")) == NULL){perror("open error");return -1;}//以只写if((fq=fopen(argv[2], "w")) == NULL){perror("open error");return -1;}char buf[128]="";int count = 0; //计数器fseek(fp, 0, SEEK_END); //光标偏移到最后count = ftell(fp);//fseek(fp, 0, SEEK_SET);//光标偏移到开头pid_t pid1 = -1;pid1 = fork();//创建一个子进程if(pid1 == 0){printf("子进程1\n"); printf("拷贝内容为后一半\n");memset(buf, 0, sizeof(buf)); //清零fseek(fp, count/2,SEEK_SET); //光标后移fseek(fq, count/2,SEEK_SET); //光标后移while(ftell(fp) != count)//文件读写到最后结束循环{int num=fread(buf,1,sizeof(buf),fp);fwrite(buf,1,num,fq);}//关闭文件fclose(fp);fclose(fq);exit(EXIT_SUCCESS);}else if(pid1 > 0){pid_t pid2 = fork(); //创建另一个子进程if(pid2 == 0){printf("子进程2\n");printf("拷贝内容为前一半\n");memset(buf, 0, sizeof(buf)); //清零int sum = 0;while(ftell(fp) < count/2){int num=fread(buf,1,sizeof(buf),fp);sum+=num;if(sum>=count/2){fwrite(buf,1,num-(sum-count/2),fq);break;}fwrite(buf,1,num,fq);} //关闭文件fclose(fp);fclose(fq);exit(EXIT_SUCCESS);}else if(pid2 > 0){wait(NULL);wait(NULL);printf("父进程已回收资源\n");}else {perror("fork error");return -1;}}else {perror("fork error");return -1;}//关闭文件fclose(fp);fclose(fq);printf("拷贝成功\n");return 0;
}