我在 Windows 下用 Ruby 写了一个 Slack 机器人,一切都很好,直到我决定在 Linux 服务器上运行它。当我访问我的 shell 并运行脚本时,它在前台正常工作,但一旦我将它移到后台,它就会停止工作。我在使用 Net::HTTP 的 HTTP 请求上遇到超时错误,或者在读取套接字时遇到 EOFError。
我在 Debian 7 上使用 Ruby 2.3。
我认为 Ruby 进程会自行停止,因为只有当我将进程返回到前台时,我才会收到错误,而且,如果我在进程处于后台时运行 ps aux
它列出了“T”(已停止)标志。
因为我想更加熟悉Linux,所以我想知道是什么导致了这个问题,而不是如何解决它。
编辑:我发现我的用户输入处理程序导致了问题。这是有问题的一点:
def input_handler
return Thread.new {
loop do
user_input = gets.chomp
end
}
end
最佳答案
问题看起来是gets
。
默认情况下,gets
从 STDIN 读取。 The documentation说:
Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line.
代码/线程将停止并等待来自键盘的提示,或者如果 STDIN 被重定向,则从管道输入中读取,或者从作为参数提供给命令行脚本的文件中读取。
关于Ruby 在后台运行时无法读取 TCP 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36315743/