我正在开发一个分布式系统,在该系统中,服务器会将大量任务分发给处理这些任务并返回结果的客户端。
服务器必须接受大小为 20Gb 量级的大文件。
服务器必须将该文件拆分成更小的部分,并将路径发送给客户端,客户端将依次对文件进行 scp 并处理它们。
我正在使用 read
和 write
来执行文件拆分,但速度慢得离谱。
代码
//fildes - Source File handle
//offset - The point from which the split to be made
//buffersize - How much to split
//This functions is called in a for loop
void chunkFile(int fildes, char* filePath, int client_id, unsigned long long* offset, int buffersize)
{
unsigned char* buffer = (unsigned char*) malloc( buffersize * sizeof(unsigned char) );
char* clientFileName = (char*)malloc( 1024 );
/* prepare client file name */
sprintf( clientFileName, "%s%d.txt",filePath, client_id);
ssize_t readcount = 0;
if( (readcount = pread64( fildes, buffer, buffersize, *offset ) ) < 0 )
{
/* error reading file */
printf("error reading file \n");
}
else
{
*offset = *offset + readcount;
//printf("Read %ud bytes\n And offset becomes %llu\n", readcount, *offset);
int clnfildes = open( clientFileName, O_CREAT | O_TRUNC | O_WRONLY , 0777);
if( clnfildes < 0 )
{
/* error opening client file */
}
else
{
if( write( clnfildes, buffer, readcount ) != readcount )
{
/* eror writing client file */
}
else
{
close( clnfildes );
}
}
}
free( buffer );
return;
}
- 有没有更快的分割文件的方法?
- 有没有什么方法客户端可以在不使用 scp 的情况下访问文件中的 block (读取而不传输)?
我正在使用 C++。如果其他语言可以执行得更快,我准备好使用它们。
最佳答案
您可以将文件放在网络服务器的范围内,然后从客户端使用 curl
curl --range 10000-20000 http://the.server.ip/file.dat > result
将获得 10000 个字节(从 10000 到 20000)
如果文件高度冗余并且网络速度很慢,可能使用压缩可以帮助加快传输速度。例如执行
nc -l -p 12345 | gunzip > chunk
在客户端然后执行
dd skip=10000 count=10000 if=bigfile bs=1 | gzip | nc client.ip.address 12345
在服务器上,您可以在不需要创建中间文件的情况下即时传输一个片段进行 gzip 压缩。
编辑
通过网络使用压缩从服务器获取文件的一部分的单个命令是
ssh server 'dd skip=10000 count=10000 bs=1 if=bigfile | gzip' | gunzip > chunk
关于c++ - 拆分大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18921855/