2023/12/06 work

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. 思维导图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值