This issue is related to this answer for one of my other questions. I was told in this answer that one can use os.kill(pid, 0)
to check whether a subprocess has terminated. If it is still running, None
is returned. If it has terminated, an OSError
is raised. This has been working fine so far, but now I'm in a situation in which os.kill(pid, 0)
still returns None
although the subprocess has already terminated. The process id was 82430 and in the activity monitor on OSX I cannot find a process with this ID anymore. However, when I open a Python shell and enter os.kill(82430, 0)
, then it still returns None
. I don't understand that.
Precisely, I check the status of the subprocess periodically in a Django view via an Ajax GET request as shown above.
Django view on server side
def monitor_process(request):
response_data = {}
try:
os.kill(int(request.GET['process_id']), 0)
response_data['process_status'] = 'running'
except OSError:
response_data['process_status'] = 'finished'
return HttpResponse(json.dumps(response_data), mimetype='application/json')
Ajax call on client side
var monitorProcess = function(processId) {
$.ajax({
dataType: 'json',
type: 'GET',
url: '/monitor_process/',
data: {'process_id': processId},
success: function(response) {
if (response.process_status == 'running') {
// Only this branch is always executed
// ...
}
else if (response.process_status == 'finished') {
// This branch never gets executed
// Stop checking for process status
// The periodic check was started by
// window.setInterval in a different Ajax call
clearInterval(monitorProcessId);
// ...
}
}
});
};
Although the process stops and disappears in the activity monitor at some point, os.kill()
apparently doesn't recognize it. Why is this the case? Thank you very much!
it's not about python, it's more about the process itself: each running process may spawn some threads around with a different PID. if the parent is not killed properly, they stay there ("zombie threads"). They are grouped altogheter with their parent under the same ID. that's why, in python, you can use
os.killpg(pgid, sig)
to kill all the group. You can check under
/proc/<PID>/task/
(where is your actual process id) for any thread spawned
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With