如何以独立于平台的方式杀死由ant exec启动的java进程?

时间:2016-06-08 16:24:50

标签: java ant jvm

我有以下build.xml代码,它使用exec在windows和mac上启动java进程(取决于运行此build.xml的操作系统),我想通过java终止这些子进程(这会很棒)如果以某种方式杀死执行此build.xml的父进程,它们会被杀死?

注意:antRunAsync.js用于运行exe文件,antRunAsync.sh用于运行jar文件。

在build.xml>>>

<target name="runscript.windows">
        <echo>This is a Windows machine.</echo>
    <exec executable="cscript.exe">
               <arg value="//NoLogo" />
               <arg value="antRunAsync.js" />  <!-- this script -->
               <arg value="${projectName}.exe" />
               <arg line="${savedTestName}"/>
            </exec>

    </target>

    <target name="runscript.mac">
        <echo>This is an Mac machine.</echo>
        <exec dir="." executable="/bin/sh">
            <arg value="./antRunAsync.sh" />
            <arg value="${projectName}.jar" />
            <arg line="${savedTestName}"/>
        </exec>
    </target>

antRunAsync.js&gt;&gt;&gt;

var WshShell = WScript.CreateObject("WScript.Shell");
var exeStr = "%comspec% /c";
var arg = "";
var windowStyle = 0;
var WshProcessEnv = WshShell.Environment("PROCESS");
var windowTitle = WshProcessEnv("ANTRUN_TITLE");
var outputFile = WshProcessEnv("ANTRUN_OUTPUT");
var OS = WshProcessEnv("OS");
var isWindowsNT = (OS == "Windows_NT");

// Loop through arguments quoting ones with spaces
for (var i = 0; i < WScript.Arguments.count(); i++) {
arg = WScript.Arguments(i);
if (arg.indexOf(' ') > 0)
    exeStr += " \"" + arg + "\"";
else
    exeStr += " " + arg;
}

WScript.Echo(exeStr);

var stdin = WshShell.Exec(exeStr).StdOut;
var stdout = WScript.StdOut;

while (!stdin.AtEndOfStream) {
var str = stdin.ReadLine();
stdout.WriteLine("Line " + (stdin.Line - 1) + ": " + str);
}

antRunAsync.sh&gt;&gt;&gt;

echo $1
echo $2
java -jar $1 $2 2>&1 | tee log.txt 

2 个答案:

答案 0 :(得分:0)

JMX是一个选项,使用它可以以独立于平台的方式终止java进程。请看下面的链接。

Is it possible to programmatically close a Java process through JMX

如果你正在寻找一个选项,杀死一个ant进程应该导致java进程终止,我不确定。

答案 1 :(得分:0)

ProcessHandle(java9)或jnr-posix提供了一般流程管理选项。早期的Java版本只能杀死通过ProcessBuilderRuntime.exec方法创建的直接子项。