[英]How to wait and kill a timeout process in Powershell
Using Powershell 2.0 in a Windows 7 desktop 在Windows 7桌面中使用Powershell 2.0
I want to create a process to run an ant command, and then wait for that process to finish in several minutes. 我想创建一个运行ant命令的进程,然后等待该进程在几分钟内完成。 If time out and the process still running then I want to kill it. 如果超时并且进程仍在运行,那么我想杀死它。
I have wrote some code as below: 我写了一些代码如下:
$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
Although the process didn't get killed, it's still running even after the Start-Sleep statement get executed. 尽管该过程没有被杀死,但即使在Start-Sleep语句执行后它仍然在运行。
I also tried with Stop-Process command, as the commented out line indicates, no luck, the process still running. 我也尝试使用Stop-Process命令,因为注释掉的行表明,没有运气,该过程仍在运行。
I may have missed something important, please give a clue. 我可能错过了一些重要的事情,请提供一些线索。
EDIT : 编辑:
It turns out there are some child processes still running in the cmd window, kill only the cmd process is not enough. 事实证明,有一些子进程仍然在cmd窗口中运行,只杀死cmd进程是不够的。
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 http://powershell.com/cs/blogs/tobias/archive/2012/05/09/managing-child-processes.aspx
I pushed in github tiny project which can be used to run process and setup timeout for him and for his child proccesses: https://github.com/burlachenkok/process_tool 我推进了github微小的项目,可以用来为他和他的孩子的proccesses运行进程和设置超时: https : //github.com/burlachenkok/process_tool
It's a sources with Makefile, and it's not a powershell script. 它是Makefile的源代码,它不是PowerShell脚本。 But hope it can be usefull for you. 但希望它对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.