gpt4 book ai didi

ruby - 尽管有 EOF,IO#select 仍返回 IO 对象——这是预期的吗?

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:21 25 4
gpt4 key购买 nike

我对 IO#select 在 Ruby 中的工作方式感到困惑。有人告诉我here它应该只返回给定的 IO 对象,如果它们已准备好被读取。但是,即使 eof? 为真,我也会返回 IO 对象。

我错过了什么吗?

这是一些表现出我的困惑的代码:

require 'open3'
stdin, stdout, stderr, thread = Open3.popen3('true')
eval_print = lambda {|code| puts "#{code} -> #{eval(code).inspect}" }
eval_print.call('stdout')
eval_print.call('stderr')
eval_print.call('select([stdout, stderr], nil, nil, 1)')
eval_print.call('stdout.eof?')
eval_print.call('stderr.eof?')
eval_print.call('stdout.gets')
eval_print.call('stderr.gets')
eval_print.call('select([stdout, stderr], nil, nil, 1)')

此代码(在 Ruby 版本 1.9.2p136 上)的输出是:

stdout -> #<IO:fd 5>
stderr -> #<IO:fd 7>
select([stdout, stderr], nil, nil, 1) -> [[#<IO:fd 5>, #<IO:fd 7>], [], []]
stdout.eof? -> true
stderr.eof? -> true
stdout.gets -> nil
stderr.gets -> nil
select([stdout, stderr], nil, nil, 1) -> [[#<IO:fd 5>, #<IO:fd 7>], [], []]

在这两种情况下,select 不应该返回 nil 吗?

最佳答案

我不怪你有点困惑,我们应该说,官方文档对 select 应该做什么有点薄弱。

IO.select 可能只是 select 系统调用的一个薄包装,所以我们将看看它(它有很好的文档记录)。来自Linux man pages :

Those listed in readfds will be watched to see if characters become available for reading (more precisely, to see if a read will not block; in particular, a file descriptor is also ready on end-of-file)

强调我的。因此,select 更多的是关于“它会阻塞”而不是“是否有字节在等我”,并且 EOF 是一种非阻塞状态,因此 select 考虑了一个处于文件结束状态以准备读取的文件描述符。

关于ruby - 尽管有 EOF,IO#select 仍返回 IO 对象——这是预期的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6260312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com