Swallowing user input while running a sub-command

帅比萌擦擦* 提交于 2019-12-05 18:50:45

You can try something like the following:

Signal.trap("INT") {}         # ignore sigint in the parent
IO.popen "sort" do |io|       # run sort in a sub process
  puts io.read                # output stdout
end
Signal.trap("INT") { exit }   # restore sigint 

while true do
  puts "looping"
  sleep 1
end

If you run the program you can type in:

$ ruby test.rb
c
d
b
^D
b
c
d
looping
looping
^C
$

or

$ ruby test.rb
c
d
b
^C
looping
looping
^C
$

It works because popen runs the command in a sub process, which has its own signal handling.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!