简体   繁体   中英

C++ Call Function When Terminated from Python Subprocess

I'm using C++, Python 3.5, and Windows 7. I'm currently calling a C++ executable from my Python code using subprocess, then terminating the executable using the following code:

open = Popen([path\to\exe])
open.terminate()

This seems unlikely, but is it possible for my C++ code to call a function in itself when Python calls terminate on it? I've found options for functions to be called when C++ is closed with the X button or by itself, but this question is too specific.

To be able to terminate your C++ code you have to first do things like

p = subprocess.Popen(["path\to\exe"])
#... do stuff
#and when you want to terminate it
p.terminate()

But you cannot call Popen again because it would spawn another instance, that would would kill immediately: useless.

When you terminate the process, it stops it right there like a kill -9 or a taskkill /F . If you want to give a chance to the process to react, do that instead of p.terminate()

Windows only:

os.system("taskkill /PID "+str(p.pid))

Unix & Windows (just read in the docs, but did not test it):

os.kill(p.pid,signal.CTRL_BREAK_EVENT)

(omitting the /F flag allows to put a handle in the C++ program to execute some exit/cleanup procedure and then exit)

Edit: to put a handle in the C++ program ( atexit is just called when you call explicitly exit , not working in that case):

(source: How can I catch a ctrl-c event? (C++) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM