Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.kill not working on spawned process

I have written my own Python-based job scheduler which uses the multiprocessing module, to spawn new jobs. I'm trying to implement a feature to kill a running process using os.kill, but it is not working. My (simplified) code look like the following:

from multiprocessing import Process
import os
...
p = Process(target=self.start_job, args=(run_dir,cmd,))
p.start()
...
def start_job(self,run_dir,cmd):
        os.chdir(run_dir)
        os.system(cmd)
        print os.getpid()
        ...

I want to take this pid that is output (e.g. 3064) and from another python session run:

import os, signal    
os.kill(3064, signal.SIGTERM)

os.kill works if I run it on the pid of the parent/spawning process, but it does not work if I execute it on the pid of the child/spawned process. In addition to SIGTERM, I've also tried a number of other signals such as SIGKILL, SIGQUIT, etc. None of them worked either. Any help would be greatly appreciated.

like image 489
Wes Avatar asked Feb 26 '15 14:02

Wes


People also ask

How do you kill a process tree in Python?

You do the equivalent with os. killpg() in Python.

What is OS kill?

kill() method in Python is used to send specified signal to the process with specified process id.


1 Answers

I solved this problem by creating a process group using the subprocess module to create the process and using os.killpg() to kill the process as described here: https://stackoverflow.com/a/4791612/2636544

like image 144
Wes Avatar answered Sep 23 '22 15:09

Wes