gpt4 book ai didi

windows - Apache Ant : Terminate process started by when ant process is terminated

转载 作者:可可西里 更新时间:2023-11-01 13:42:18 27 4
gpt4 key购买 nike

我有一个 ant 任务,它使用 <exec> 执行冗长的构建操作. Ant 由 Windows 命令行中的批处理文件启动。如果我通过关闭窗口来终止 ant 任务,则进程由 <exec> 启动继续运行。当 ant 进程本身终止时,如何实现终止生成的进程?

Ant 1.10.0 在带有 Oracle JDK 8 的 Windows 7 x64 上使用。启动进程的任务类似于:

<exec executable="${make.executable}" dir="${compile.dir}" failonerror="true">
<arg line="${make.parameters}" />
</exec>

java关闭命令行窗口时,运行 ant 的进程被正确终止。

最佳答案

这里有一个可能的解决方案:

  • 批处理脚本使用名为 antPidFile 的参数启动 Ant。
  • Ant 脚本使用 Java jps 工具获取运行 Ant 脚本的 java.exe 进程的 PID。
  • Ant 脚本将 PID 写入 antPidFile
  • Ant 脚本生成子进程。
  • Ant 退出,控制权返回批处理脚本。
  • 批处理脚本将之前 Ant 脚本的 PID 加载到一个变量中。
  • 批处理脚本使用内置的 wmic 工具来识别 Ant 生成的进程。
  • 批处理脚本使用内置的 taskkill 工具来终止 Ant 生成的所有子进程(和孙进程)。

build.xml

<project name="ant-kill-child-processes" default="run" basedir=".">
<target name="run">
<fail unless="antPidFile"/>
<exec executable="jps">
<!-- Output the arguments passed to each process's main method. -->
<arg value="-m"/>
<redirector output="${antPidFile}">
<outputfilterchain>
<linecontains>
<!-- Match the arguments provided to this Ant script. -->
<contains value="Launcher -DantPidFile=${antPidFile}"/>
</linecontains>
<tokenfilter>
<!-- The output of the jps command follows the following pattern: -->
<!-- lvmid [ [ classname | JARfilename | "Unknown"] [ arg* ] [ jvmarg* ] ] -->
<!-- We want the "lvmid" at the beginning of the line. -->
<replaceregex pattern="^(\d+).*$" replace="\1"/>
</tokenfilter>
</outputfilterchain>
</redirector>
</exec>
<!-- As a test, spawn notepad. It will persist after this Ant script exits. -->
<exec executable="notepad" spawn="true"/>
</target>
</project>

批处理脚本

setlocal

set DeadAntProcessIdFile=ant-pid.txt

call ant "-DantPidFile=%DeadAntProcessIdFile%"

rem The Ant script should have written its PID to DeadAntProcessIdFile.
set /p DeadAntProcessId=< %DeadAntProcessIdFile%

rem Kill any lingering processes created by the Ant script.
for /f "skip=1 usebackq" %%h in (
`wmic process where "ParentProcessId=%DeadAntProcessId%" get ProcessId ^| findstr .`
) do taskkill /F /T /PID %%h

关于windows - Apache Ant : Terminate process started by <exec> when ant process is terminated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41526217/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com