Why does os.kill (pid, 0) return None even though the process is complete?

This issue is related to this answer on one of my other questions. In this answer, they told me that you can use os.kill(pid, 0) to check if the subprocess has completed. If it is still running, returns None . If it is completed, an OSError is OSError . While this works, but now I am in a situation where os.kill(pid, 0) still returns None , although the subprocess has already been completed. The process ID was 82430, and in the OSX activity monitor, I can no longer find the process with this ID. However, when I open the Python shell and os.kill(82430, 0) , it still returns None . I do not understand this.

Precisely, I check the status of the subprocess periodically in the Django view using an Ajax GET request, as shown above.

Server side Django view

 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 the 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 on the activity monitor at some point, os.kill() does not seem to recognize it. Why is this so? Thank you very much!

+4
source share
1 answer

it's not about python, it's more about the process itself: each running process can spawn some threads with a different PID. if the parent is not killed properly, they remain there ("zombie streams"). They are grouped together with their parents under one identifier. therefore, in python you can use

 os.killpg(pgid, sig) 

to kill the whole group. you can check

 /proc/<PID>/task/ 

(where is your actual process id) for any thread spawned

+5
source

All Articles