了解sendfile()和splice() [英] Understanding sendfile() and splice()

查看:212
本文介绍了了解sendfile()和splice()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sendfile()可用于将数据从文件"描述符传输到套接字"描述符,以便将数据从机器A获取到机器B.是否有可能在接收端从文件"获取数据.套接字"描述符到具有类似零复制语义的文件?我认为sendfile()在这里无济于事,因为sendfile()需要数据源为页面/缓冲区"缓存.我的理解正确吗? splice()在这种情况下可以提供帮助吗?

sendfile() can be used to transmit data from a "file" descriptor to a "socket" descriptor in order to get data from machine A to machine B. Is it possible to get the data at the receiving end from the "socket" descriptor to a file with similar zero-copy semantics? I think sendfile() doesn't help here because sendfile() needs the source of data to be "page/buffer" cache. Is my understanding correct? Can splice() help in this situation?

推荐答案

对于sendfile的限制,您是正确的.是的,splice可以提供帮助,但这并不简单:splice要求至少源文件描述符或目标文件描述符之一是管道.因此,您不能直接从套接字splice到纯文件描述符.

You're correct about the limitation of sendfile for this. And yes, splice can help, but it's not trivial: splice requires that at least one of the source or target file descriptors be a pipe. So you can't directly splice from a socket to a plain file descriptor.

从概念上讲,您可以执行以下操作:

Conceptually, what you can do to make it work is:

  • 像往常一样设置入站套接字fd和输出文件fd
  • 使用 pipe(2) 创建管道li>
  • 循环中:
    • 使用 splice
    • 也使用splice从管道的读取端写入文件
    • setup your inbound socket fd and your output file fd as you would normally
    • create a pipe with pipe(2)
    • in a loop:
      • read from the socket to the write side of the pipe with splice
      • write from the read side of the pipe to the file with splice also

      重复最后的步骤,直到读取所有数据为止.

      Repeat the last steps until all the data is read.

      在Linux中使用sendfile进行零复制( )和splice()具有此技术的实现.

      这篇关于了解sendfile()和splice()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆