How to create a process using ProcessBuilder in Java 9?

Java 9 added ProcessHandle interface to Process API to enhance Process class. An instance of the ProcessHandle interface identifies a local process that allows us to query process status and managing processes, and ProcessHandle.Info allows us to use local code because of the need to obtain the PID of a local process.

ProcessBuilder class can be used to create separate operating system processes. In the below example, we can create a process of "notepad" application by using the ProcessBuilder class.

Example

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

public class ProcessBuilderTest {
   public static void main(String args[]) throws IOException {
      <strong>ProcessBuilder </strong>pb = new <strong>ProcessBuilder</strong>("<strong>notepad.exe</strong>");
      String np = "Not Present";
      <strong>Process </strong>p = pb.<strong>start()</strong>;
      <strong>ProcessHandle.Info</strong> info = p.<strong>info()</strong>;

      System.out.printf("Process ID : %s%n", p.<strong>pid()</strong>);
      System.out.printf("Command name : %s%n", info.<strong>command()</strong>.orElse(np));
      System.out.printf("Command line : %s%n", info.<strong>commandLine()</strong>.orElse(np));

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

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

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

The above example launches the notepad application as below

Output

<strong>Process ID : 3728
Command name : C:\WINDOWS\System32\notepad.exe
Command line : Not Present
Start time: 2020-04-20T18:06:30.378
Arguments : Not Present
User : Tutorialspoint\User</strong>
Updated on: 2020-04-20T16:24:53+05:30

451 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements