2017-01-07 164 views
2

我有一個螞蟻任務,它使用<exec>執行冗長的構建操作。 Ant由Windows命令行中的批處理文件啓動。如果我通過關閉窗口終止螞蟻任務,由<exec>開始的進程繼續運行。當螞蟻進程本身終止時,我該如何終止生成的進程?Apache Ant:螞蟻進程終止時終止進程<exec>

螞蟻1.10.0在Windows 7 X64的使用Oracle JDK 8.開始處理任務中使用是類似於:

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

java過程運行ant關閉命令行窗口時正確終止。

回答

1

這裏是一個可能的解決方案:

  • 批處理腳本啓動螞蟻名爲antPidFile參數。
  • 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 
+0

我不認爲如果用戶關閉命令行窗口繼續進行批處理腳本執行。雖然有趣的做法,謝謝! – DevCybran