maynull
maynull

Reputation: 2046

How to run a function when a subprocess is terminated?

I have 2 python codes, one of which is mar.py and the other is sub.py

## mar.py
import os
import subprocess
import time

print('MASTER PID: ', os.getpid())

proc = subprocess.Popen(["D:\Miniconda3\python.exe", r"C:\Users\J\Desktop\test\sub.py"], shell=False)

def terminator():
    proc.terminate()

time.sleep(5)
terminator()

mar.py simply creates a subprocess using sub.py and terminates it in 5 seconds.

## sub.py
import atexit
import time
import os

print('SUB PID: ', os.getpid())

os.chdir("C:\\Users\\J\\Desktop\\test")

def handle_exit():
    with open("foo.txt", "w") as f:
        f.write("Life is too short, you need python")

atexit.register(handle_exit)

while True:
    print('alive')
    time.sleep(1)

I thought foo.txt would be created before the subprocess of sub.py is terminated, but nothing happens. If I run sub.py on its own and terminate it, it creates foo.txt as I planned. What does make this difference and how could I still make it create foo.txt even when it's run as a subprocess?

I'm using Windows 10(64bit) and Python 3.6.5 (32bit)

Upvotes: 1

Views: 209

Answers (1)

theamk
theamk

Reputation: 1663

When you say you "terminate" sub.py, does this mean you press Ctrl+C on it? On windows, this actually sends CTRL_C_EVENT to the process, unlike terminate() method which calls TerminateProcess WinAPI method.

Looks like you need to import signal and then do proc.send_signal(signal.CTRL_C_EVENT) instead of proc.terminate()

Upvotes: 2

Related Questions