Java 9 provied pretty way to get information of the Process
, but I still don't know how to get the CommandLine
& arguments
of the process:
Process p = Runtime.getRuntime().exec("notepad.exe E:\\test.txt");
ProcessHandle.Info info = p.toHandle().info();
String[] arguments = info.arguments().orElse(new String[]{});
System.out.println("Arguments : " + arguments.length);
System.out.println("Command : " + info.command().orElse(""));
System.out.println("CommandLine : " + info.commandLine().orElse(""));
Result:
Arguments : 0
Command : C:\Windows\System32\notepad.exe
CommandLine :
But I am expecting:
Arguments : 1
Command : C:\Windows\System32\notepad.exe
CommandLine : C:\Windows\System32\notepad.exe E:\\test.txt
JDK-8176725 indicates that this feature is not implemented yet for Windows. Here is an easy but slow workaround:
/**
* Returns the full command-line of the process.
* <p>
* This is a workaround for
* <a href="https://stackoverflow.com/a/46768046/14731">https://stackoverflow.com/a/46768046/14731</a>
*
* @param processHandle a process handle
* @return the command-line of the process
* @throws UncheckedIOException if an I/O error occurs
*/
private Optional<String> getCommandLine(ProcessHandle processHandle) throws UncheckedIOException {
if (!isWindows) {
return processHandle.info().commandLine();
}
long desiredProcessid = processHandle.pid();
try {
Process process = new ProcessBuilder("wmic", "process", "where", "ProcessID=" + desiredProcessid, "get",
"commandline", "/format:list").
redirectErrorStream(true).
start();
try (InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
BufferedReader reader = new BufferedReader(inputStreamReader)) {
while (true) {
String line = reader.readLine();
if (line == null) {
return Optional.empty();
}
if (!line.startsWith("CommandLine=")) {
continue;
}
return Optional.of(line.substring("CommandLine=".length()));
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With