Linux 高级I/O函数-sendfile

sendfile函数在Linux中用于在两个文件描述符之间直接传输数据,减少了用户空间和内核空间的数据拷贝,提高了效率。本文通过示例展示了如何使用sendfile将文件内容发送到套接字连接的客户端,从而实现零拷贝传输。
摘要由CSDN通过智能技术生成

sendfile函数在两个文件描述符之间直接传递数据(完全在内核中传递),从而避免了内核缓冲区和用户缓冲区之间的数据拷贝,效率很高,又称为zero-copy。

函数原型:

#include<sys/sendfile.h>

ssize_t sendfile(int out_fd, int in_fd, off_t* offset, size_t count); 

其中in_fd就可以认为是读入的文件操作符,out_fd是连接sock_fd,offset为偏移量,为空则从默认的其实位置开始,count参数指定在文件描述符in_fd和out_fd之间传输的字节数。sendfile成功时返回传输的字节数,失败返回-1,并设置errno。

函数演示:

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cassert>
#include <cstdio>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <libgen.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/uio.h>
#include <sys/sendfile.h>

#define filename "sendfile.txt"

int main(int argc, char *argv[]) {
    if (argc <= 2) {
        printf("Usage : %s ip_address port_number\n", basename(argv[0]));
        return 1;
    }

    const char *ip = argv[1];
    int port = atoi(argv[2]);

    int filefd = open(filename, O_RDONLY);
    assert(filefd > 0);
    struct stat stat_buf;
    fstat(filefd,&stat_buf);

    struct sockaddr_in address;

    bzero(&address, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_port = htons(port);
    address.sin_addr.s_addr = inet_addr(ip);

    int sock = socket(PF_INET, SOCK_STREAM, 0);
    assert(sock >= 0);

    int ret = bind(sock, (struct sockaddr *) &address, sizeof(address));
    assert(ret != -1);

    struct sockaddr_in client;
    socklen_t client_addrlength = sizeof(client);

    ret = listen(sock, 5);
    assert(ret != -1);


    int confd = accept(sock, (struct sockaddr *) &client, &client_addrlength);
    if (confd < 0)
        printf("errno is : %d\n", errno);
    else {
        sendfile(confd, filefd,NULL,stat_buf.st_size);
        close(confd);
    }


    close(sock);
    return 0;


}

上面的程序从sendfile.txt文件中读取返回给连接的客户端。用telnet 测试就返回到控制台了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

顾文繁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值