-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec_with_timeout.rb
65 lines (47 loc) · 971 Bytes
/
exec_with_timeout.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env ruby
require 'rubygems'
require 'timeout'
require 'pty'
class Exec_With_Timeout
def self.main
begin
# spawn process
PTY.spawn @command do |r,w,pid|
@pid = pid
@read = r
@write = w
# start timeout
Timeout.timeout @timeout do
loop do
# get output line
begin
line = @read.gets
@output << line if !line.nil?
rescue
end
# check if process is still running
begin
Process.getpgid @pid
rescue
raise Timeout::Error
end
end
end
end
# catch timeout
rescue Timeout::Error
begin
Process.kill 9, @pid
rescue
end
end
@output
end
def self.exec(command, timeout)
@pid = nil
@command = command
@timeout = timeout
@output = ""
self.main
end
end