数分間実行されるプロセスを開始するコマンドを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ですが、プロセスが開始されたようには見えません。プログラムの実行が完了すると、プロセスが開始され、なぜそれが起こるのかわかりません。
また、コンソールウィンドウを表示するには、Googleから次のコマンドを使用する必要があることがわかりました。
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加