My script opens TCP connection and reads data from server. If server does not respond I try to interrupt the script with Ctrl+C, but it does not work. The only way to terminate the script is to kill process in task man开发者_如何学编程ager. Any ideas how to interrupt such script?
require 'socket'
host = '...'
port = ...
s = TCPSocket.open(host, port)
while line = s.gets
puts line.chop
end
s.close
trap("SIGINT") { clean up; exit}
I noticed, that it I cick Ctrl+C while waiting response from server, and some time latter response comes, the application terminates. But while I wait on socket (s.gets), the Ctrl+C has no effect.
So I solved the problem by running network code in a different thread.
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
Now I can terminate script by typing any character. But still would be nice to know about alternative solution.
On Windows, type Ctrl+Pause
精彩评论