如何在 Powershell 中等待和终止超时进程 [英] How to wait and kill a timeout process in Powershell
问题描述
在 Windows 7 桌面上使用 Powershell 2.0
Using Powershell 2.0 in a Windows 7 desktop
我想创建一个进程来运行 ant 命令,然后等待该进程在几分钟内完成.如果超时并且进程仍在运行,那么我想杀死它.
I want to create a process to run an ant command, and then wait for that process to finish in several minutes. If time out and the process still running then I want to kill it.
我写了一些代码如下:
$p = Start-Process "cmd.exe" '/c ant execute' -PassThru -RedirectStandardOutput $log_file_path
Wait-Process -id $p.ID -timeout 100
if(!$p.hasExited) {
echo "kill the process"
$p.Kill()
#Stop-Process $p.ID
}
Start-Sleep -s 30
# continue to do other things
虽然进程没有被杀死,但即使在 Start-Sleep 语句被执行之后它仍然在运行.
Although the process didn't get killed, it's still running even after the Start-Sleep statement get executed.
我也尝试过使用 Stop-Process 命令,如注释掉的行所示,不走运,进程仍在运行.
I also tried with Stop-Process command, as the commented out line indicates, no luck, the process still running.
我可能漏掉了一些重要的东西,请提供线索.
I may have missed something important, please give a clue.
原来cmd窗口里还有一些子进程在运行,只杀掉cmd进程是不够的.
It turns out there are some child processes still running in the cmd window, kill only the cmd process is not enough.
我终于用以下代码完成了工作:
I finally get the job done with following code:
if(!$p.hasExited) {
echo "kill the process"
taskkill /T /F /PID $p.ID
#$p.Kill()
#Stop-Process $p.ID
}
推荐答案
如果要杀死整个进程树,还需要找到并停止子进程.
If you want to kill the entire process tree, you need to also find and stop the child processes.
这是一篇很好的文章,解释了它并向您展示了如何做到这一点:
Here's a good article that explains it and shows you how to do that:
http://powershell.com/cs/blogs/tobias/archive/2012/05/09/managing-child-processes.aspx
这篇关于如何在 Powershell 中等待和终止超时进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!