David Callanan
David Callanan

Reputation: 5968

atexit handler not responding to signals

I have two python files:

a.py:

import subprocess, time, os, signal

myprocess = subprocess.Popen("b.py", shell=True)
time.sleep(2)
os.kill(myprocess.pid, signal.SIGTERM)

b.py:

import atexit

def cleanup():
    print "Cleaning up things before the program exits..."

atexit.register(cleanup)

print "Hello world!"

while True:
    pass

a.py is spawning b.py and after 2 seconds it is killing the process. The problem is that I want the cleanup function to call in b.py before it gets killed but I can't get it to work.

I also tried SIGKILL and SIGINT in the os.kill function but neither worked for me.

Current output (a.py):

Hello, World!
(2 seconds later, program ends)

Expected output (a.py):

Hello, World!
(2 seconds later)
Cleaning up things before the program exits...
(program ends)

Upvotes: 3

Views: 833

Answers (1)

wim
wim

Reputation: 362647

Use a different signal for Windows platform: signal.CTRL_C_EVENT

Put some more sleep into a.py, otherwise the child process does not get a chance to clean up before the parent process exits:

import subprocess, time, os, signal
myprocess = subprocess.Popen("b.py", shell=True)
time.sleep(2)
os.kill(myprocess.pid, signal.CTRL_C_EVENT)
time.sleep(2)

I also want to discourage you from using the shell, if you don't actually need the shell features:

import subprocess, time, os, signal, sys
myprocess = subprocess.Popen([sys.executable, "b.py"])

Linux/macOS users: signal.CTRL_C_EVENT doesn't exist, you want signal.SIGINT.

Upvotes: 3

Related Questions