简体   繁体   English

C ++:如何检查外部程序是否正在运行?

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

I run an external program with C++: 我使用C ++运行外部程序:

_wsystem(exec);

I want to kill the process if it runs for more than n seconds. 如果进程运行了n秒以上,我想终止该进程。 I can do it in Python like this: 我可以这样在Python中执行此操作:

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++? 在C ++中,p.poll()和p.terminate()的替代方法是什么?

Thank you 谢谢

PS Solutions involving WinAPI are welcome too. 也欢迎涉及WinAPI的PS解决方案。

There is a MS knowledge base entry describing how to cleanly terminate applications. 有一个MS知识库条目,描述了如何彻底终止应用程序。 Essentially if you just want to kill the process and don't care about potential side effects then you can just use TerminateProcess . 本质上,如果您只是想TerminateProcess进程而不关心潜在的副作用,则可以使用TerminateProcess

The Windows API way to check if a process is still running is GetExitCodeProcess . 用于检查进程是否仍在运行的Windows API方法是GetExitCodeProcess

If you can resolve this issue on the OS level and not using Python. 如果您可以在操作系统级别而不使用Python解决此问题。 Eg might look into 例如,可能会调查

http://devel.ringlet.net/sysutils/timelimit/ http://devel.ringlet.net/sysutils/timelimit/

Or you man check the resource module of Python: 或者您可以检查Python的资源模块:

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

I can only comment on Unix, since that's the platform I know best. 我只能在Unix上发表评论,因为这是我最了解的平台。

  • p.poll() becomes kill(pid, 0) p.poll()变为kill(pid, 0)
  • p.terminate() becomes kill(pid, SIGTERM) p.terminate()变为kill(pid, SIGTERM)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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