【问题标题】:Can't interrupt/terminate Ruby script with Ctrl+C on Windows无法在 Windows 上使用 Ctrl+C 中断/终止 Ruby 脚本
【发布时间】:2010-12-04 17:52:39
【问题描述】:

我的脚本打开 TCP 连接并从服务器读取数据。如果服务器没有响应,我尝试使用 Ctrl+C 中断脚本,但它不起作用。终止脚本的唯一方法是在任务管理器中终止进程。任何想法如何中断这样的脚本?

require 'socket'

host = '...'
port = ...

s = TCPSocket.open(host, port)

while line = s.gets
  puts line.chop
end

s.close 

【问题讨论】:

    标签: ruby interrupt terminate


    【解决方案1】:

    trap("SIGINT") { 清理;退出}

    【讨论】:

    • 这将处理由 Ctrl+C 生成的信号。我的问题是代码在 s.gets 上等待时没有生成这个信号。
    【解决方案2】:

    我注意到,在等待来自服务器的响应时,我点击了 Ctrl+C,并且稍后的响应来了,应用程序终止了。但是当我在 socket (s.gets) 上等待时,Ctrl+C 不起作用。

    所以我通过在不同的线程中运行网络代码解决了这个问题。

    require 'socket'
    
    host = '...'
    port = ...
    
    t = Thread.new do
      s = TCPSocket.open(host, port)
    
      while line = s.gets
        puts line.chop
      end
    
      s.close 
    end
    
    STDIN.getc
    

    现在我可以通过键入任何字符来终止脚本。但仍然很高兴了解替代解决方案。

    【讨论】:

      【解决方案3】:

      在 Windows 上,按 Ctrl+Pause

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-30
        • 2016-06-23
        • 2013-11-17
        • 1970-01-01
        • 2018-07-11
        • 2019-12-09
        • 1970-01-01
        相关资源
        最近更新 更多