1、使用两个线程完成两个文件的拷贝,分支线程1拷贝前一半,分支线程2拷贝后一半,主线程回收两个分支线程的资源
#include <myhead.h>
int copy_file(const char *srcfile,const char *destfile,int start,int len);
struct Buff
{
const char *srcfile;
const char *destfile;
int len;
int flag;
};
void *task(void *arg)
{
struct Buff *buff = (struct Buff *)arg;
if(buff->flag == 1)
{
copy_file(buff->srcfile,buff->destfile,0,buff->len/2);
}else if (buff->flag == 2)
{
copy_file(buff->srcfile,buff->destfile,buff->len/2,buff->len-buff->len/2);
}
}
int get_file_len(const char *srcfile,const char *destfile)
{
//以只读打开源文件
int sfd = open(srcfile,O_RDONLY);
if(sfd == -1)
{
perror("open srcfile error");
return -1;
}
//以创建的形式打开目标文件
int dfd = open(destfile,O_WRONLY|O_CREAT|O_TRUNC,0664);
if(dfd == -1)
{
perror("open destfile error");
return -1;
}
int size = lseek(sfd,0,SEEK_END);
//关闭文件
close(sfd);
close(dfd);
return size;
}
int copy_file(const char *srcfile,const char *destfile,int start,int len)
{
//以只读的形式打开源文件
int sfd = open(srcfile,O_RDONLY);
if(sfd == -1)
{
perror("open srcfile error");
return -1;
}
int dfd = open(destfile,O_WRONLY);
if(dfd == -1)
{
perror("open destfile error");
return -1;
}
lseek(sfd,start,SEEK_SET);
lseek(dfd,start,SEEK_SET);
char buf[128]="";
int sum =0;
while(1)
{
//从源文件中读取数据
int res = read(sfd,buf,sizeof(buf));
sum += res;
if(res==0||sum>len)
{
write(dfd,buf,res-(sum-len));
break;
}
write(dfd,buf,res);
}
close(sfd);
close(dfd);
printf("拷贝成功\n");
}
int main(int argc, const char *argv[])
{
if(argc != 3) //判断是否传入两个文件
{
printf("input file error\n");
return -1;
}
const char *srcfile = argv[1];
const char *destfile = argv[2];
int len = get_file_len(srcfile,destfile); //求出源文件的长度
struct Buff buff1={srcfile,destfile,len,1};
struct Buff buff2={srcfile,destfile,len,2};
//定义两个线程变量
pthread_t tid1,tid2;
//创建两个线程
if((pthread_create(&tid1,NULL,task,&buff1)) != 0)
{
printf("tid1 创建失败\n");
return -1;
}
if((pthread_create(&tid2,NULL,task,&buff2)) != 0)
{
printf("tid2 创建失败\n");
return -1;
}
//阻塞等两个线程的回收
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}