0

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.

dsolimano
  • 8,870
  • 3
  • 48
  • 63
Alex
  • 34,581
  • 26
  • 91
  • 135
  • Which platform are you using? Unlike Python (which abstracts these operations for you in a semi-portable way), in C, each operating system does it differently. – C. K. Young Mar 30 '11 at 06:00
  • Bummer, I don't know Windows well enough to help you there. But I posted a Unix answer, anyway. :-P – C. K. Young Mar 30 '11 at 06:02

3 Answers3

1

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.

ChrisWue
  • 18,612
  • 4
  • 58
  • 83
0

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:

http://docs.python.org/library/resource.html

0

I can only comment on Unix, since that's the platform I know best.

  • p.poll() becomes kill(pid, 0)
  • p.terminate() becomes kill(pid, SIGTERM)
C. K. Young
  • 219,335
  • 46
  • 382
  • 435