【无标题】IO进程线程


void cp(const char *src_file,const char *dst_file,int start,int end){
	FILE *fp_src = fopen(src_file,"r");
	FILE *fp_dst = fopen(dst_file,"a");
	if(fp_src == NULL || fp_dst == NULL){
		perror("fopen error");
		return;
	}
	fseek(fp_src,start,SEEK_SET);
	fseek(fp_dst,start,SEEK_SET);
	char buf[1];
	while(ftell(fp_src) < end){
		fread(buf,sizeof(char),sizeof(buf),fp_src);
		fwrite(buf,sizeof(char),sizeof(buf),fp_dst);
	}
	fclose(fp_src);
	fclose(fp_dst);
	printf("拷贝成功\n");
}
 
int main(int argc, const char *argv[])
{
	char src_file[] = "../1/01test.c";
	char dst_file[] = "./aaa.txt";
	FILE *fp = fopen(src_file,"r");
	if(fp == NULL){
		perror("fopen error");
		return -1;
	}
	fseek(fp,0,SEEK_END);
	int end = ftell(fp);
	int mid = end / 2;
	pid_t pid;
	pid = fork();
	if(pid < 0){
		perror("fork error");
		return -1;
	}else if(pid == 0){
		printf("子进程已创建\n");
		cp(src_file,dst_file,mid,end);
		exit(EXIT_SUCCESS);
	}else{
		printf("父进程已创建\n");
		cp(src_file,dst_file,0,mid);
		wait(NULL);
	}
	fclose(fp);
	return 0;


2> 使用三个进程完成两个文件的拷贝,父进程拷贝前三分之一,子进程1拷贝中间三分之一,子进程2拷贝后三分之一,父进程要阻塞回收所有子进程资源

#include <myhead.h>
 
void cp(const char *src_file,const char *dst_file,int start,int end){
	FILE *fp_src = fopen(src_file,"r");
	FILE *fp_dst = fopen(dst_file,"a");
	if(fp_src == NULL || fp_dst == NULL){
		perror("fopen error");
		return;
	}
	fseek(fp_src,start,SEEK_SET);
	fseek(fp_dst,start,SEEK_SET);
	char buf[1] = {};
	while(ftell(fp_src) < end){
		fread(buf,sizeof(char),sizeof(buf),fp_src);
		fwrite(buf,sizeof(char),sizeof(buf),fp_dst);
	}
	fclose(fp_src);
	fclose(fp_dst);
	printf("拷贝成功\n");
}
 
int main(int argc, const char *argv[])
{
	char src_file[] = "../1/01test.c";
	char dst_file[] = "./bbb.txt";
	FILE *fp = fopen(src_file,"r");
	if(fp == NULL){
		perror("fopen error");
		return -1;
	}
	fseek(fp,0,SEEK_END);
	int end3 = ftell(fp);	
	int end1 = end3/3;
	int end2 = end3/3*2;
	pid_t pid1;
	pid1 = fork();
	if(pid1 < 0){
		perror("fork1 error");
		return -1;
	}else if(pid1 == 0){
		printf("子进程1创建成功\n");
		cp(src_file,dst_file,end1,end2);
		exit(EXIT_SUCCESS);
	}else{
		pid_t pid2;
		pid2 = fork();
		if(pid2 < 0){
			perror("fork2 error");
			return -1;
		}else if(pid2 == 0){
			sleep(3);
			printf("子进程2创建成功\n");
			cp(src_file,dst_file,end2,end3);
			exit(EXIT_SUCCESS);
		}else{
			printf("父进程创建成功\n");
			cp(src_file,dst_file,0,end1);
			wait(NULL);
			wait(NULL);
		}
	}
	return 0;

————————————————
版权声明:本文为CSDN博主「小坤儿~」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_54147737/article/details/132367561

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值