In Java, you can use the ProcessBuilder
class to execute system processes and gather information about them. Starting from Java 9, you can also use the ProcessHandle
class to obtain details about system processes more conveniently. Here's a basic example:
public class ProcessDetailsExample {
public static void main(String[] args) {
// Run a system process
ProcessBuilder processBuilder = new ProcessBuilder("ls");
try {
Process process = processBuilder.start();
// Get the process handle
ProcessHandle processHandle = process.toHandle();
// Print process details
System.out.println("Process ID: " + processHandle.pid());
System.out.println("Command: " + processHandle.info().command().orElse("N/A"));
System.out.println("Arguments: " + String.join(" ", processHandle.info().arguments().orElse(new String[]{})));
System.out.println("Start time: " + processHandle.info().startInstant().orElse(null));
// Wait for the process to finish
int exitCode = process.waitFor();
System.out.println("Exit Code: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this example, the ProcessBuilder
is used to start a system process (in this case, the ls
command). The Process object is obtained, and then its ProcessHandle
is retrieved. Various details about the process can be obtained using methods provided by the ProcessHandle.Info
class.
Note: The actual system command (ls
in this case) will vary depending on the operating system. Adjust the command accordingly for Windows or other operating systems.
Keep in mind that dealing with system processes can have security implications, and it's important to handle exceptions properly and ensure that the processes you execute are secure and well-controlled.