Apache Ant:Ant进程终止时,终止进程由<exec>启动

Cyb*_*ran 5 windows ant cmd batch-file exec

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

在Windows 7 x64和Oracle JDK 8上使用Ant 1.10.0。启动该过程的任务类似于:

<exec executable="${make.executable}" dir="${compile.dir}" failonerror="true">
    <arg line="${make.parameters}" />
</exec>
Run Code Online (Sandbox Code Playgroud)

所述java关闭命令行窗口时运行过程蚂蚁正确终止。

Cha*_*uis 2

这是一个可能的解决方案:

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

构建.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>
Run Code Online (Sandbox Code Playgroud)

批处理脚本

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
Run Code Online (Sandbox Code Playgroud)