0

I am facing a problem to kill a spawned subprocess from a different thread on program exit. I have even tried atexit.register but no help. Please see me as new to python. Please see my code below

bgp = BigGrapePines()
bs = BigSourers()
    def run():
        proc = subprocess.Popen("java MyAppPerformStunts", stdout=outfile, stderr=subprocess.STDOUT,
                                                cwd=self.workingdirectory, shell=True)   
        proc.wait()
        return proc 
#----------------------------
    def callfunc(a,b):
        procobj = bs.run() #Going to take hrs to complete
        print("Process PID is given below")
        print(procobj.pid)
        bgp.setppid(procobj.pid)

    def cleanup():
        prid = bgp.getppid()
        if prid is None:
            pass
        else:
            try:
                os.kill(prid,signal.SIGTERM)
            except OSError:
                print("Cannot Kill the Process" + str(prid))
        pass


    def main(): 
        thread = Thread(target = callfunc, args = ("Latest","1"))
        thread.daemon = True
        thread.start()
        time.sleep(20)
        performoperations();
        cleanup()


if __name__ == "__main__":
    main()      

performoperations() will run for few minutes. On completing main thread, I want to kill my subprocess which opened on run(). Since I am getting the pid as the return value of run(), I am not able to proceed further Any help will be hihgly appreciated

Debianeese
  • 154
  • 1
  • 2
  • 9
  • why are you calling `proc.wait()` in `run()`? this waits until the process have terminated – eli Feb 03 '16 at 11:37
  • [there is no need to use threads to run several processes concurrently](http://stackoverflow.com/q/14533458/4279) (`Popen()` does not wait for the child process to finish). Drop `proc.wait()`, drop `Thread()`, and call `callfunc()` directly (it might be easier to call `proc.terminate()` instead of the pid manipulations + `os.kill()`). In general, see [How to make child process die after parent exits?](http://stackoverflow.com/q/284325/4279) – jfs Feb 04 '16 at 15:29

0 Answers0