java – 执行命令显示控制台窗口并获取进程的句柄

我正在尝试从Java运行一个命令,它将启动一个运行几分钟的进程.我需要触发命令并获取进程句柄并继续循环中的其他操作.我会定期监控该过程是否仍处于活动状态.

我还需要显示控制台窗口以显示用户的进程输出.

目前,我已尝试运行Runtime和ProcessBuilder类的方法来运行我的命令,但它们都没有帮助我实现我的目标.

示例代码:

//Changing the directory and running Maven exec: java command on the POM file in that directory.

String cmd = "cd C:/Test & mvn exec:java"; 
String finalCmd = "cmd /c \""+ cmd +"\"";

Process process = Runtime.getRuntime().exec(finalCmd);
Thread.sleep(10);
boolean alive = process.isAlive();

变量alive的值为True,但我没有看到该过程已开始.程序执行完成后,只有这个过程开始,我不确定为什么会这样.

另外为了显示控制台窗口,我从谷歌发现我需要使用以下命令:

String finalCmd = "cmd /c start cmd.exe /c \"" + cmd + "\"";

但是,有了这个,进程立即开始,但我没有得到进程句柄,因为我发现alive变量显示为false.

有人知道如何实现这一目标吗?我很好,如果不可能同时做两个,但至少我需要启动进程执行并获取句柄以便稍后在我的代码中监视进程状态.

最佳答案
这是一个使用WMIC的解决方案.

public static void main( String[] args ) throws Exception {

    // Vars
    Process process;
    String output;

    // Execution
    process = Runtime.getRuntime().exec("cmd /c wmic process call create calc.exe | findstr ProcessId");
    output = readTrimmedOutput(process.getInputStream());
    System.out.println("Output from command: " + output);

    // Basic string manipulation to get process id
    String str_proc_id = output.split(" = ")[1].replace(";","");
    System.out.println("ProcessId is: " + str_proc_id);

    // Some thread delay that you can comment/uncomment for testing if running or not
    Thread.sleep(5000);

    // Finding if process is still running
    process = Runtime.getRuntime().exec("cmd /c wmic process get processid | findstr " + str_proc_id);
    output = readTrimmedOutput(process.getInputStream());

    boolean isRunning = output.contains(str_proc_id);
    System.out.println("Is process still running? " + isRunning);

}

private static String readTrimmedOutput(InputStream is) throws Exception {
    BufferedReader breader = new BufferedReader(new InputStreamReader(is));
    String line = breader.readLine();
    return line != null ? line.trim() : "";
}

样本输出

Output from command: ProcessId = 6480;
ProcessId is: 6480
Is process still running? true

要显示/显示cmd控制台,请将某些行更改为:

// Execution
String your_command = "cmd.exe /c \"dir\"";
process = Runtime.getRuntime().exec("cmd /c wmic process call create \"" + your_command + "\" | findstr ProcessId");

参考文献:

https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx

https://www.computerhope.com/wmic.htm

转载注明原文:java – 执行命令显示控制台窗口并获取进程的句柄 - 代码日志