C++: how to check whether an external program is running?
-
14-11-2019 - |
Question
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
.
OTHER TIPS
If you can resolve this issue on the OS level and not using Python. E.g. might look into
http://devel.ringlet.net/sysutils/timelimit/
Or you man check the resource module of Python:
I can only comment on Unix, since that's the platform I know best.
p.poll()
becomeskill(pid, 0)
p.terminate()
becomeskill(pid, SIGTERM)