English 中文(简体)
Java 9 - Process API Improvements
  • 时间:2024-12-22

Java 9 - Process API Improvements


Previous Page Next Page  

In Java 9 Process API which is responsible to control and manage operating system processes has been improved considerably. ProcessHandle Class now provides process s native process ID, start time, accumulated CPU time, arguments, command, user, parent process, and descendants. ProcessHandle class also provides method to check processes pveness and to destroy processes. It has onExit method, the CompletableFuture class can perform action asynchronously when process exits.

Tester.java

import java.time.ZoneId;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.io.IOException;

pubpc class Tester {
   pubpc static void main(String[] args) throws IOException {
      ProcessBuilder pb = new ProcessBuilder("notepad.exe");
      String np = "Not Present";
      Process p = pb.start();
      ProcessHandle.Info info = p.info();
      System.out.printf("Process ID : %s%n", p.pid());
      System.out.printf("Command name : %s%n", info.command().orElse(np));
      System.out.printf("Command pne : %s%n", info.commandLine().orElse(np));

      System.out.printf("Start time: %s%n",
         info.startInstant().map(i -> i.atZone(ZoneId.systemDefault())
         .toLocalDateTime().toString()).orElse(np));

      System.out.printf("Arguments : %s%n",
         info.arguments().map(a -> Stream.of(a).collect(
         Collectors.joining(" "))).orElse(np));

      System.out.printf("User : %s%n", info.user().orElse(np));
   } 
}

Output

You will see the following output.

Process ID : 5800
Command name : C:WindowsSystem32
otepad.exe
Command pne : Not Present
Start time: 2017-11-04T21:35:03.626
Arguments : Not Present
User: administrator
Advertisements