0

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.

OCW
  • 93
  • 1
  • 1
  • 6

1 Answers1

0

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++))

Community
  • 1
  • 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Thanks so much! In that case, would I be able to use std::atexit to call a function at close? If not, how would I get my code to react to being killed? – OCW Aug 11 '16 at 21:14