【问题标题】:Apache Ant: Terminate process started by <exec> when ant process is terminatedApache Ant:终止 ant 进程时由 <exec> 启动的进程
【发布时间】:2017-01-07 20:31:13
【问题描述】:

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

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

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

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

【问题讨论】:

  • 我也有同样的问题...

标签: windows batch-file ant cmd exec


【解决方案1】:

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

  • 批处理脚本使用名为 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

【讨论】:

  • 如果用户关闭命令行窗口,我认为批处理脚本不会继续执行。有趣的方法,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多