1. 使用两个子进程完成两个文件的拷贝,子进程1拷贝前一半内容,子进程2拷贝后一半内容,父进程用于回收两个子进程的资源
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <myhead.h>
int get_file_len(const char * srcFile){
//文件IO
int srcId;
if((srcId = open(srcFile,O_RDONLY)) == -1){
perror("srcFile open error");
return -1;
}
//得到文件大小
int len = lseek(srcId,0,SEEK_END);
close(srcId);
return len;
}
int create_desc_file(const char * descFile){
int descId;
if((descId = open(descFile,O_RDONLY | O_CREAT|O_TRUNC,0664)) == -1){
perror("descFile1 open error");
return -1;
}
close(descId);
return descId;
}
int file_copy(const char * srcFile,const char * descFile,int start,int len){
//打开原文件
int srcId;
if((srcId = open(srcFile,O_RDONLY)) == -1){
perror("srcFile open error");
return -1;
}
//打开目标文件
int descId;
if((descId = open(descFile,O_WRONLY)) == -1){
perror("descFile2 open error");
return -1;
}
//控制光标
lseek(srcId,start,SEEK_SET);
lseek(descId,start,SEEK_SET);
char rea[100];
int res =0;
int sum =0;
while(1){
res = read(srcId,rea,sizeof(rea));
sum += res;
if(sum >= len || res ==0){
write(descId,rea,res-(sum -len));
//记得痛处循环
break;
}
//写文件
write(descId,rea,res);
}
//关闭文件
close(srcId);
close(descId);
}
int main(int argc, const char *argv[])
{
if(argc != 3){
printf("please enter file");
return -1;
}
//定义源文件大小
int len = get_file_len(argv[1]);
create_desc_file(argv[2]);
pid_t pid1 = -1;
pid1 = fork();
//子进程1
if(pid1 == 0){
//前一半
file_copy(argv[1],argv[2],0,len/2);
printf("前一半拷贝完成\n");
exit(EXIT_SUCCESS);
}else if(pid1 > 0 ){
pid_t pid2 = -1;
pid2 = fork();
//子进程2
if(pid2 == 0){
file_copy(argv[1],argv[2],len/2,len-len/2);
printf("后一半拷贝完成\n");
exit(EXIT_SUCCESS);
}else if(pid2 > 0){
//在父进程中回收 进程
wait(NULL);
wait(NULL);
}else{
perror("fork 2 error");
return -1;
}
}else{
perror("fork 1 error");
return -1;
}
return 0;
}
2. 思维导图