- 论坛徽章:
- 0
|
利用mmap拷贝发送文件。
因为mmap的文件offset必须是系统页面大大小,所以每次就发送一个页面大小大内容。
/*
* sender.c
*
* Created on: 2008-12-5
* Author: sody
*/
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char** argv)
{
struct sockaddr_in srvadd;
int srvsock, dstfile, i, pagecnt, leftcnt;
long pagesize;
struct stat info;
char* maper;
if (argc != 3)
{
fprintf(stderr, "There must be two arguments.\n");
return -1;
}
if ((dstfile = open(argv[2], O_RDONLY)) == -1)
{
perror("Fail to open file to transfer");
return -1;
}
if (fstat(dstfile, &info) == -1)
{
perror("Fail to get the information about the file");
return -1;
}
if (!(pagesize = sysconf(_SC_PAGESIZE)))
{
perror("Fail to get the system page size");
return -1;
}
leftcnt = info.st_size % pagesize;
pagecnt = (info.st_size - leftcnt) / pagesize;
/*preparing connecting to the server*/
bzero(&srvadd, sizeof(srvadd));
srvadd.sin_family = AF_INET;
srvadd.sin_port = ntohs(2235);
if (inet_aton(argv[1], &srvadd.sin_addr) == 0)
{
perror("Fail to get the server address by argument");
return -1;
}
if ((srvsock = socket(PF_INET,SOCK_STREAM, 0)) == -1)
{
perror("Fail to make the socket fd");
return -1;
}
if (connect(srvsock, (struct sockaddr*) (&srvadd), sizeof(srvadd)) == -1)
{
perror("Fail to connect to the server");
return -1;
}
for (i = 0; i pagecnt; i++)
{/*sending the bulk*/
if ((maper = mmap(NULL,pagesize, PROT_READ,MAP_PRIVATE, dstfile, i
* pagesize)) == MAP_FAILED)
{
perror("Fail to map file into memroy");
goto END;
}
write(srvsock, maper, pagesize);
munmap(maper, pagesize);
}
if (leftcnt != 0)
{/*sending the left*/
if ((maper = mmap(NULL,leftcnt, PROT_READ,MAP_PRIVATE, dstfile, i
* pagesize)) == MAP_FAILED)
{
perror("Fail to map file into memroy");
goto END;
}
write(srvsock, maper, leftcnt);
munmap(maper, leftcnt);
}
END: close(srvsock);
close(dstfile);
return 0;
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/18481/showart_1685797.html |
|