IO作业4.0

思维导图

创建出三个进程完成两个文件之间拷贝工作,子进程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;
}

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值