Search code examples
pythonc++windowsexternal-processprocess-management

C++: how to check whether an external program is running?


I run an external program with C++:

_wsystem(exec);

I want to kill the process if it runs for more than n seconds. I can do it in Python like this:

p = subprocess.Popen(self.temp_exec, shell=True)

cur_time = 0.0

while cur_time < self.time_limit:
            if p.poll() != None:
                # Kill the process
                                    p.terminate()
                break
            time.sleep(0.1)
            cur_time += 0.1

What's the alternative of p.poll() and p.terminate() in C++?

Thank you

P.S. Solutions involving WinAPI are welcome too.


Solution

  • There is a MS knowledge base entry describing how to cleanly terminate applications. Essentially if you just want to kill the process and don't care about potential side effects then you can just use TerminateProcess.

    The Windows API way to check if a process is still running is GetExitCodeProcess.