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
|
# File 'lib/looped/tools/run_command.rb', line 17
def call(command:, timeout: DEFAULT_TIMEOUT)
pid = T.let(nil, T.nilable(Integer))
output = +''
begin
stdin, stdout_err, wait_thr = Open3.popen2e(command)
pid = wait_thr.pid
stdin.close
reader = Thread.new { stdout_err.read }
if wait_thr.join(timeout)
output = reader.value
exit_status = wait_thr.value
"Exit code: #{exit_status.exitstatus}\n#{output}"
else
reader.kill
Process.kill('TERM', pid)
sleep 0.1
begin
Process.kill('KILL', pid) if wait_thr.alive?
rescue Errno::ESRCH
end
wait_thr.join
"Error: Command timed out after #{timeout} seconds"
end
rescue StandardError => e
"Error: #{e.message}"
ensure
stdout_err&.close rescue nil
end
end
|