免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1047 | 回复: 0
打印 上一主题 下一主题

利用mmap拷贝发送文件 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-12-08 14:24 |只看该作者 |倒序浏览
利用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
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP