ruby timeouts and system commands
I think you have to kill
it manually:
require 'timeout'
puts 'starting process'
pid = Process.spawn('sleep 20')
begin
Timeout.timeout(5) do
puts 'waiting for the process to end'
Process.wait(pid)
puts 'process finished in time'
end
rescue Timeout::Error
puts 'process not finished in time, killing it'
Process.kill('TERM', pid)
end
How to timeout subprocess in Ruby
Ruby ships witrh the Timeout module.
require 'timeout'
res = ""
status = Timeout::timeout(5) {res = `#{cmd}`} rescue Timeout::Error
# a bit of experimenting:
res = nil
status = Timeout::timeout(1) {res = `sleep 2`} rescue Timeout::Error
p res # nil
p status # Timeout::Error
res = nil
status = Timeout::timeout(3) {res = `sleep 2`} rescue Timeout::Error
p res # ""
p status # ""
Kill linux command in ruby if timed-out
Not sure if this illustrates it but for example 2 ruby files:
#slow_proceess.rb
puts 'starting.... waiting...'
10.times do
puts "slow process runing..."
sleep 1
end
puts 'done exiting'
#fast.rb
pid = Process.spawn('ruby slow_process.rb')
# after x seconds we can kill the process with
`kill -9 #{pid}`
Or in your example use instance variable to access it outside of the block and also rescue error (thanks @tadman):
begin
Timeout::timeout(5) {
@pid = Process.spawn('sleep 30; echo 1')
}
rescue Timeout::Error
puts "#{@pid} process has timed out"
end
# do stuff
Changing behavior of gets, when reading from command line, in Ruby
Check the docs:
If
Kernel.gets
sees thatARGV
is set, it uses them as filenames to
feed instead of reading from stdin. So use an expicit:$stdin.gets
Best way of implementing timeouts on ruby sockets
From what I understand now, it is easiest (not necessarily best--depends on your needs) just to avoid this problem of trying to have my socket connection attempt time out as well as my socket.read time out. Since my script is simple and I am using Ruby 1.8.7, I am using the system_timer gem (ruby's timeout library is not reliable for Ruby 1.8.x and system_timer gets around timeout's issues for Ruby 1.8.x).
http://systemtimer.rubyforge.org/
The documentation is good.
Related Topics
Why Doesn't "Rails S" Work from the App Directory
Assign/Replace Params Hash in Rails
Railstutorial - Chapter 8.4.3 - Test Database Not Clearing After Adding User in Integration Test
Functional Code Examples in Ruby
Rails 3.1 - Has_And_Belongs_To_Many Deprecated
What's the Best Way to Unit Test Protected & Private Methods in Ruby
Ruby Ternary Operator Without Else
Sinatra Configuring Environments on the Fly
Does Ruby Call Initialize Method Automatically
Trying to Install Ruby-Filemagic on Snow Leopard Using Brew Rather Than Ports
Windows/Ruby/Rails Install --- .Cannot Load Such File -- SQLite3/Sqlite3_Native Windows
Traversing a Hash Recursively in Ruby
How to Send Message Using Gmail API with Ruby Google API Client
Sass::Syntaxerror: File to Import Not Found or Unreadable: Compass in Production