IO 作业 24/2/21

1、使用多线程完成两个文件的拷贝,第一个线程拷贝前一半,第二个线程拷贝后一半,主线程回收两个线程的资源

#include <myhead.h>
//定义分支线程1
void *task1(void *arg)
{
	int fdr=-1;
	//只读打开被复制文件
	if((fdr=open("./111.txt",O_RDONLY))==-1)
	{
		perror("open_r error");
		return NULL;
	}
	int fdw=-1;
	//只写打开目标文件文件
	if((fdw=open("./222.txt",O_WRONLY|O_CREAT,0664))==-1)
	{
		perror("open_w error");
		return NULL;
	}
	//文件字节大小
	off_t size=lseek(fdr,0,SEEK_END);
	//光标
	lseek(fdr,0,SEEK_SET);
	lseek(fdw,0,SEEK_SET);
	//定义数组读取字符
	char strR[10]="";
	int sum=0;
	while(1)
	{
		int res=read(fdr,strR,sizeof(strR));
		sum+=res;
		if(sum>=size/2||res==0)
		{
			write(fdw,strR,res-(sum-size/2));
			break;
		}
		write(fdw,strR,res);
	//	printf("111\n");
	}
	//关闭文件
	close(fdr);
	close(fdw);
	pthread_exit;
}
//定义分支线程2
void *task2(void *arg)
{
	int fdr=-1;
	//只读打开被复制文件
	if((fdr=open("./111.txt",O_RDONLY))==-1)
	{
		perror("open_r error");
		return NULL;
	}
	int fdw=-1;
	//只写打开目标文件文件
	if((fdw=open("./222.txt",O_WRONLY|O_CREAT,0664))==-1)
	{
		perror("open_w error");
		return NULL;
	}
	//文件字节大小
	off_t size=lseek(fdr,0,SEEK_END);
	//光标
	lseek(fdr,size/2,SEEK_SET);
	lseek(fdw,size/2,SEEK_SET);
	//定义数组读取字符
	char strR[10]="";
	int sum=0;
	while(1)
	{
		int res=read(fdr,strR,sizeof(strR));
		sum+=res;
		if(sum>=size/2||res==0)
		{
			write(fdw,strR,res-(sum-(size-size/2)));
			break;
		}
		write(fdw,strR,res);
	//	printf("111\n");
	}
	//关闭文件
	close(fdr);
	close(fdw);
	pthread_exit;
}
int main(int argc, const char *argv[])
{
	//定义线程号变量
	pthread_t tid1=-1;
	pthread_t tid2=-1;
	//创建线程1
	if(pthread_create(&tid1,NULL,task1,NULL)!=0)
	{
		printf("tid1 create error\n");
		return -1;
	}
	//创建线程2
	if(pthread_create(&tid2,NULL,task2,NULL)!=0)
	{
		printf("tid2 create error\n");
		return -1;
	}
	//回收线程资源
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	return 0;
}

2、思维导图

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值