确定可读文件描述符是否是管道的读取端
我想使用 splice
来零复制数据STDIN_FILENO
到文件描述符(可以是常规文件、字符或块设备、FIFO 或可以使用 打开
)。为了使用splice
,from文件描述符或to文件描述符必须是管道的适当末端,因此通常管道是当程序员想要将数据从非管道到非管道进行零复制时,创建它作为中间缓冲区。但是,如果 STDIN_FILENO 已经是管道的读取端,那么我可以跳过该步骤并尝试直接从 STDIN_FILENO 拼接到另一个文件描述符。因此,我希望能够确定 STDIN_FILENO 是否是管道的读取端。
是否有 Linux 系统调用可以确定 STDIN_FILENO 是否是管道的读取端?
I would like to use splice
to zero-copy data from STDIN_FILENO
to a file descriptor (which could be to a regular file, char or block device, FIFO, or anything that can be opened with open
). In order to use splice
, either the from file descriptor or to file descriptor must be the appropriate end of a pipe, so generally a pipe is created to serve as an intermediary buffer when the programmer wants to zero-copy data from non-pipe to non-pipe. However, if STDIN_FILENO
is already the read end of a pipe, then I could skip that step and attempt to splice directly from STDIN_FILENO
to the other file descriptor. Therefore, I would like to be able to determine whether STDIN_FILENO
is the read end of a pipe.
Is there a Linux system call that can determine whether STDIN_FILENO
is the read end of a pipe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要获取有关打开的 fd 的信息,可以使用 fstat()。我猜结果的 st_mode 应该是管道的 S_IFIFO 。或者,/proc/self/fd/ 和 /proc/self/fdinfo/ 也提供有关文件描述符的一些信息。请记住 /proc 是特定于 Linux 的。
但是,我认为首先尝试使用 splice() 可能会更容易,如果失败(使用 EINVAL?),则可以使用您的魔法。
To get information about an open fd, you can use fstat(). I'd guess that st_mode of the result should be S_IFIFO for a pipe. Alternatively, /proc/self/fd/ and /proc/self/fdinfo/ also provide some information about a file descriptor. Keep in mind that /proc is linux-specific.
However, I think it might be easier to just try to use splice() first and if it fails (with EINVAL?) fall back to your magic.
作为替代方案,如果“fd 与管道、套接字或 FIFO 关联”,
lseek()
将失败并返回ESPIPE
。因此,无操作lseek(fd, 0, SEEK_CUR)
会告诉您文件描述符是否是其中任何一个。就我而言,这涵盖了我感兴趣的所有案例。
As an alternative,
lseek()
will fail withESPIPE
if "fd is associated with a pipe, socket, or FIFO." So a no-oplseek(fd, 0, SEEK_CUR)
will tell you if the file descriptor is any of these.In my situation, this covers all of the cases I was interested in.