linux将数据从文件描述符管道传输到fifo [英] linux pipe data from file descriptor into a fifo

查看:188
本文介绍了linux将数据从文件描述符管道传输到fifo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说,我知道文件描述符fd在我的进程中已打开以供读取.我想将数据从此fd传递到一个fifo中,该数据可在进程外读取,以免避免在fd上调用pollselect以及手动读取/转发数据的方式.能做到吗?

Lets say I know that a file descriptor fd is open for reading in my process. I would like to pipe data from this fd into a fifo that is available for reading outside my of process, in a way that avoids calling poll or select on fd and manually reading/forwarding data. Can this be done?

推荐答案

您的意思是要求操作系统从现在开始一直在幕后进行此操作?像I/O重定向一样?

You mean ask the OS to do that behind the scenes on an ongoing basis from now on? Like an I/O redirection?

不,你不能那样做.

您可以生成一个除了读取文件fd和写入管道fd之外什么都不做的线程.为了避免在read(2)write(2)系统调用中复制内存的开销,可以使用sendfile(out_fd, in_fd, NULL, 4096)告诉内核将页面从in_fd复制到out_fd.请参见手册页.

You could spawn a thread that does nothing but read the file fd and write the pipe fd, though. To avoid the overhead of copying memory around in read(2) and write(2) system calls, you can use sendfile(out_fd, in_fd, NULL, 4096) to tell the kernel to copy a page from in_fd to out_fd. See the man page.

通过splice(2),您可能会获得更好的结果,因为它是为与文件和管道一起使用而设计的. sendfile(2)过去要求out_fd是套接字. (设计用于零复制,例如从Web服务器在TCP套接字上发送静态数据.)

You might have better results with splice(2), since it's designed for use with files and pipes. sendfile(2) used to require out_fd to be a socket. (Designed for zero-copy sending static data on TCP sockets, e.g. from a web server.)

Linux确实具有异步I/O ,所以您可以将发生在后台的读取或写入排队.这不是一个好选择,因为您不能将一个fd的副本排队到另一个fd. (无异步splice(2)sendfile(2)).即使有,它也会有一个特定的请求大小,而不是一劳永逸地永久复制.在AFAIK中,线程已成为执行异步I/O的首选方法,而不是POSIX AIO工具.

Linux does have asynchronous I/O, so you can queue up a read or write to happen in the background. That's not a good choice here, because you can't queue up a copy from one fd to another. (no async splice(2) or sendfile(2)). Even if there was, it would have a specific request size, not a fire-and-forget keep copying-forever. AFAIK, threads have become the preferred way to do async I/O, rather than the POSIX AIO facilities.

这篇关于linux将数据从文件描述符管道传输到fifo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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