Managing Operating System Processes - Java Native OS

Java examples for Native OS:Process

Introduction

Utilize the Process API to obtain information regarding individual operating system processes or destroy them.

import java.lang.ProcessBuilder; 
import java.lang.Process; 
import java.time.Instant; 
import java.time.Duration; 
import java.time.temporal.ChronoUnit; 

public class Main { 
  public static void printProcessDetails(ProcessHandle currentProcess){ 
    ProcessHandle.Info currentProcessInfo = currentProcess.info(); 
    if ( currentProcessInfo.command().orElse("").equals("")){ 
      return; 
    } 

    System.out.println("Process id: " + currentProcess.getPid()); 

    System.out.println("Command: " + currentProcessInfo.command().orElse("")); 

    String[] arguments = currentProcessInfo.arguments().orElse(new String[]{}); 
    if ( arguments.length != 0){ 
      System.out.print("Arguments: "); 
      for(String arg : arguments){ 
        System.out.print(arg + " "); 
      } 
      System.out.println(); 
    } 
    //Get the start time of the process 
     System.out.println("Started at: " + currentProcessInfo.startInstant().orElse(Instant. 
     now()).toString()); 
    //Get the time the process ran for 
     System.out.println("Ran for: " + currentProcessInfo.totalCpuDuration().orElse(Duration. 
     ofMillis(0)).toMillis() + "ms"); 
    //Get the owner of the process 
    System.out.println("Owner: " + currentProcessInfo.user().orElse("")); 
  } 
  public static void main(String[] args){ 
    ProcessHandle current = ProcessHandle.current(); 
    ProcessHandle.Info currentInfo = current.info(); 
    System.out.println("Command Line Process: " + currentInfo.commandLine()); 
    System.out.println("Process User: " + currentInfo.user()); 
    System.out.println("Process Start Time: " + currentInfo.startInstant()); 
    System.out.println("PID: " + current.getPid()); 

    ProcessBuilder pb = new ProcessBuilder("ls"); 
    try { 
    Process process = pb.start(); 
    System.out.println(process); 
    process.children().forEach((p) ->{System.out.println(p);}); 
      ProcessHandle pHandle = process.toHandle(); 
     System.out.println("Parent of Process: " + pHandle.parent()); 
    } catch (java.io.IOException e){ 
      System.out.println(e); 
    } 

  } 
}

Related Tutorials