Javaで外部コマンドを実行する
WindowsとLinuxでコマンドを切り替える.
ProcessBuilderを使う.
標準出力/標準エラー出力のハンドリング
標準出力と標準エラー出力をまとめて,ファイルに書き出すのが良さそう.
ストリームを取り回すのは面倒.
Windows上だとsjisになっているのが面倒.
code:std
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
pb.redirectOutput(new File("stdouterr.log"));
コマンドの組み立て
パイプするにはcmd.exe /cが必要.
コマンドや引数をまとめると動かなかった. NG "xargs -n 1 taskkill /F /T /PID" パイプするにはbash -cが必要
killとバッククォート以下を区切ると上手く行かなかった.
code:java
try (Socket socket = new Socket()) {
final int port = 1234;
socket.bind(new InetSocketAddress("localhost", port));
} catch (IOException e) {
log.warn(e, e);
try {
String appName = getClass().getSimpleName();
List<String> command;
if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
command = List.of("cmd.exe", "/c", "wmic.exe", "process", "where",
"CommandLine like '%" + appName + "'", "get", "ProcessId", "|", "xargs", "-n", "1",
"taskkill", "/F", "/T", "/PID");
} else {
command =
List.of("bash", "-c", "kill ps -ef | grep " + appName + " | awk '{print $2;}'");
}
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
// pb.redirectOutput(new File("stdouterr.log"));
Process proc = pb.start();
proc.waitFor(3000, TimeUnit.SECONDS);
} catch (IOException | InterruptedException e1) {
log.warn(e1, e1);
}
}