Skip to content

Commit 27b4746

Browse files
author
Vladimir Kotal
committed
extra effort to terminate the process after timeout
1 parent d875dd1 commit 27b4746

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

tools/command.py

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import threading
2828
import time
2929
import resource
30+
import signal
3031

3132

3233
class TimeoutException(Exception):
@@ -92,18 +93,45 @@ def __init__(self, logger, timeout, condition, p):
9293
self.start()
9394
self.exception = None
9495

96+
def terminate(self, p):
97+
"""
98+
Make sure the process goes away.
99+
"""
100+
p.terminate()
101+
102+
# The following code tries more methods to terminate
103+
# the process and is specific to Unix.
104+
if os.name == 'posix':
105+
timeout = self.timeout
106+
term_signals = [signal.SIGINT, signal.SIGKILL]
107+
for sig in term_signals:
108+
timeout = timeout / 2 # exponential back-off
109+
self.logger.info("Sleeping for {} seconds".
110+
format(timeout))
111+
time.sleep(timeout)
112+
113+
if p.poll() is None:
114+
self.logger.info("Command with PID {} still alive,"
115+
" killing with signal {}".
116+
format(p.pid, sig))
117+
p.send_signal(sig)
118+
else:
119+
self.logger.info("Command with PID {} is gone".
120+
format(p.pid))
121+
break
122+
95123
def run(self):
96124
with self.condition:
97125
if not self.condition.wait(self.timeout):
98126
p = self.popen
99127
self.logger.info("Terminating command {} with PID {} "
100128
"after timeout of {} seconds".
101129
format(p.args, p.pid, self.timeout))
102-
p.terminate()
103130
self.exception = TimeoutException("Command {} with pid"
104131
" {} timed out".
105132
format(p.args,
106133
p.pid))
134+
self.terminate(p)
107135
else:
108136
return None
109137

@@ -207,7 +235,8 @@ def close(self):
207235

208236
if self.timeout:
209237
time_condition = threading.Condition()
210-
self.logger.debug("Setting timeout to {}".format(self.timeout))
238+
self.logger.debug("Setting timeout to {} seconds".
239+
format(self.timeout))
211240
timeout_thread = TimeoutThread(self.logger, self.timeout,
212241
time_condition, p)
213242

0 commit comments

Comments
 (0)