可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a while
loop consistently listening to incoming connections and outputting them to console. I would like to be able to issue commands via the console without affecting the output. I've tried:
Thread.new do while true input = gets.chomp puts "So I herd u sed, \"#{input}\"." #Commands would be in this scope end end
However, that seems to pause my entire script until input is received; and even then, some threads I have initiated before this one don't seem to execute. I've tried looking at TCPSocket's select()
method to no avail.
回答1:
Not sure where are the commands you want to "continue running" in your example. Try this small script:
Thread.new do loop do s = gets.chomp puts "You entered #{s}" exit if s == 'end' end end i = 0 loop do puts "And the script is still running (#{i})..." i += 1 sleep 1 end
Reading from STDIN is done in a separate thread, while the main script continues to work.
回答2:
Ruby uses green threads, so blocking system calls will block all threads anyway. An idea:
require 'io/wait' while true if $stdin.ready? line = $stdin.readline.strip p "line from stdin: #{line}" end p "really, I am working here" sleep 0.1 end