java pid 获取句柄_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");

参考文献:

标签:java,command-line,process

来源: https://codeday.me/bug/20190522/1153193.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值