思维导图
拷贝文件
#include<head.h>
struct a
{
const char *yuan;
const char *cp;
};
pthread_mutex_t mutex;
//计算文件大小
int lenth(const char *yuan,const char *cp)
{
int fd,fa;
if((fd=open(yuan,O_RDONLY))==-1)
{
perror("open yuan error");
return -1;
}
if((fa=open(cp,O_WRONLY|O_CREAT|O_TRUNC,0664))==-1)
{
perror("open cp error");
return -1;
}
int len=lseek(fd,0,SEEK_END);
close(fd);
close(fa);
return len;
}
int copy(const char *yuan,const char *cp,int start,int len)
{
int fd,fa;
//以只读的形式打开源文件
if((fd=open(yuan,O_RDONLY))==-1)
{
perror("open fd error");
return -1;
}
if((fa=open(cp,O_WRONLY))==-1)
{
perror("open fa error");
return -1;
}
//定光标位置
lseek(fd,start,SEEK_SET);
lseek(fa,start,SEEK_SET);
char s[100]="";
int res=0;
int sum=0;
while(1)
{
res=read(fd,s,sizeof(s));
sum+=res;
if(sum>=len || res==0)
{
write(fa,s,res-(sum-len));
break;
}
write(fa,s,res);
}
close(fa);
close(fd);
}
//子线程1
void *task1(void *arg)
{
int len=lenth(((struct a*)arg)->yuan,((struct a*)arg)->cp);
//拷贝文件内容到len/2
copy(((struct a*)arg)->yuan,((struct a*)arg)->cp,0,len/2);
pthread_exit(NULL);
}
//子线程2
void *task2(void *arg)
{
int len=lenth(((struct a*)arg)->yuan,((struct a*)arg)->cp);
copy(((struct a*)arg)->yuan,((struct a*)arg)->cp,0,len/2);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(argc !=3 )
{
printf("input error\n");
return -1;
}
struct a a={argv[1],argv[2]};
pthread_t tid1=0;
pthread_t tid2=0;
if(pthread_create(&tid1,NULL,task1,&a)!=0)
{
printf("tid1 create error\n");
return -1;
}
if(pthread_create(&tid2,NULL,task2,&a)!=0)
{
printf("tid2 create error\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
printf("拷贝成功\n");
return 0;
}
互斥