#include <myhead.h>
#include <pthread.h>
//结构体描述,把好多个变量传给这个拷贝子进程
struct Info
{
//四个数据分别是:源文件,目标文件,光标位置,拷贝大小
//俩个线程共用一个线程体,二者的区别就在于光标和拷贝大小
char *s;
char *d;
int start;
int size;
};
/*
* function: 求文件长度
* @param [ in] 源文件,目标文件
* @param [out]
* @return 文件长度
*/
int file_len ( const char *sf , const char *df )
{
//定义俩个文件描述符
int sfd;
int dfd;
//先打开源文件,并创建和清空目标文件
if ( (sfd = open ( sf , O_RDONLY )) == -1 )
{
printf ( "打开失败" );
return -1;
}
if ( (dfd = open ( df , O_RDONLY|O_CREAT|O_TRUNC , 0664 )) == -1 )
{
printf ( "打开失败" );
return -1;
}
//计算长度
int len = lseek ( sfd , 0 , SEEK_END );
//关闭俩个文件
close ( sfd );
close ( dfd );
return len;
}
//定义线程体,把copy的功能就封装在线程体里
void *copy ( void *info )
{
//定义俩个文件描述符
int sfd;
int dfd;
//强转
struct Info data;
data = *(struct Info *)info;
//打开源文件和目标文件
if ( (sfd = open ( data.s , O_RDONLY )) == -1 )
{
perror ( "" );
return NULL;
}
if ( (dfd = open ( data.d , O_WRONLY )) == -1 )
{
perror ( "" );
return NULL;
}
//定义瓢
char buf[32] = "";
//先移动俩个文件的光标
lseek ( sfd , data.start , SEEK_SET );
lseek ( dfd , data.start , SEEK_SET );
//读源文件,写入目标文件,完成拷贝
int count = 0;
while ( 1 )
{
int ret = read ( sfd , buf , sizeof(buf) );
count += ret;
if (ret == 0 || count >= data.size )
{
write ( dfd , buf , ret - (count - data.size) );
break;
}
write ( dfd , buf , ret );
}
}
int main(int argc, const char *argv[])
{
//判断
if ( argc != 3 )
{
printf ( "少参数" );
return -1;
}
//搞个函数去求出源文件的大小,并且创建清空目标文件
int len = file_len ( argv[1] , argv[2] );
//创建变量去保存线程号
pthread_t tid1;
pthread_t tid2;
//定义俩个结构体变量,并初始化
struct Info first = { argv[1] , argv[2] , 0 , len/2 };
struct Info second = { argv[1] , argv[2] , len/2 , len-(len/2) };
//用函数创建俩个线程
if ( pthread_create (&tid1 , NULL , copy , &first) )
{
perror ( "" );
return -1;
}
if ( pthread_create (&tid2 , NULL , copy , &second) )
{
perror ( "" );
return -1;
}
while ( 1 );
return 0;
}