1 /*
   2  * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.lang;
  26 
  27 import java.time.Duration;
  28 import java.time.Instant;
  29 import java.util.Optional;
  30 import java.util.concurrent.CompletableFuture;
  31 import java.util.stream.Stream;
  32 
  33 /**
  34  * ProcessHandle identifies and provides control of native processes. Each
  35  * individual process can be monitored for liveness, list its children,
  36  * get information about the process or destroy it.
  37  * By comparison, {@link java.lang.Process Process} instances were started
  38  * by the current process and additionally provide access to the process
  39  * input, output, and error streams.
  40  * <p>
  41  * The native process ID is an identification number that the
  42  * operating system assigns to the process.
  43  * The range for process id values is dependent on the operating system.
  44  * For example, an embedded system might use a 16-bit value.
  45  * Status information about a process is retrieved from the native system
  46  * and may change asynchronously; processes may be created or terminate
  47  * spontaneously.
  48  * The time between when a process terminates and the process id
  49  * is reused for a new process is unpredictable.
  50  * Race conditions can exist between checking the status of a process and
  51  * acting upon it. When using ProcessHandles avoid assumptions
  52  * about the liveness or identity of the underlying process.
  53  * <p>
  54  * Each ProcessHandle identifies and allows control of a process in the native
  55  * system. ProcessHandles are returned from the factory methods {@link #current()},
  56  * {@link #of(long)},
  57  * {@link #children}, {@link #allChildren}, {@link #parent()} and
  58  * {@link #allProcesses()}.
  59  * <p>
  60  * The {@link Process} instances created by {@link ProcessBuilder} can be queried
  61  * for a ProcessHandle that provides information about the Process.
  62  * ProcessHandle references should not be freely distributed.
  63  *
  64  * <p>
  65  * A {@link java.util.concurrent.CompletableFuture} available from {@link #onExit}
  66  * can be used to wait for process termination, and possibly trigger dependent
  67  * actions.
  68  * <p>
  69  * The factory methods limit access to ProcessHandles using the
  70  * SecurityManager checking the {@link RuntimePermission RuntimePermission("manageProcess")}.
  71  * The ability to control processes is also restricted by the native system,
  72  * ProcessHandle provides no more access to, or control over, the native process
  73  * than would be allowed by a native application.
  74  *
  75  * @implSpec
  76  * In the case where ProcessHandles cannot be supported then the factory
  77  * methods must consistently throw {@link java.lang.UnsupportedOperationException}.
  78  * The methods of this class throw {@link java.lang.UnsupportedOperationException}
  79  * if the operating system does not allow access to query or kill a process.
  80  *
  81  * @see Process
  82  * @since 1.9
  83  */
  84 public interface ProcessHandle extends Comparable<ProcessHandle> {
  85 
  86     /**
  87      * Returns the native process ID of the process. The native process ID is an
  88      * identification number that the operating system assigns to the process.
  89      *
  90      * @return the native process ID of the process
  91      * @throws UnsupportedOperationException if the implementation
  92      *         does not support this operation
  93      */
  94     long getPid();
  95 
  96     /**
  97      * Returns an {@code Optional<ProcessHandle>} for an existing native process.
  98      *
  99      * @param pid a native process ID
 100      * @return an {@code Optional<ProcessHandle>} of the PID for the process;
 101      *         the {@code Optional} is empty if the process does not exist
 102      * @throws SecurityException if a security manager has been installed and
 103      *         it denies RuntimePermission("manageProcess")
 104      * @throws UnsupportedOperationException if the implementation
 105      *         does not support this operation
 106      */
 107     public static Optional<ProcessHandle> of(long pid) {
 108         return ProcessHandleImpl.get(pid);
 109     }
 110 
 111     /**
 112      * Returns a ProcessHandle for the current process. The ProcessHandle cannot be
 113      * used to destroy the current process, use {@link System#exit System.exit} instead.
 114      *
 115      * @return a ProcessHandle for the current process
 116      * @throws SecurityException if a security manager has been installed and
 117      *         it denies RuntimePermission("manageProcess")
 118      * @throws UnsupportedOperationException if the implementation
 119      *         does not support this operation
 120      */
 121     public static ProcessHandle current() {
 122         return ProcessHandleImpl.current();
 123     }
 124 
 125     /**
 126      * Returns an {@code Optional<ProcessHandle>} for the parent process.
 127      * Note that Processes in a zombie state usually don't have a parent.
 128      *
 129      * @return an {@code Optional<ProcessHandle>} of the parent process;
 130      *         the {@code Optional} is empty if the child process does not have a parent
 131      *         or if the parent is not available, possibly due to operating system limitations
 132      * @throws SecurityException if a security manager has been installed and
 133      *         it denies RuntimePermission("manageProcess")
 134      */
 135     Optional<ProcessHandle> parent();
 136 
 137     /**
 138      * Returns a snapshot of the current direct children of the process.
 139      * A process that is {@link #isAlive not alive} has zero children.
 140      * <p>
 141      * <em>Note that processes are created and terminate asynchronously.
 142      * There is no guarantee that a process is {@link #isAlive alive}.
 143      * </em>
 144      *
 145      * @return a Stream of ProcessHandles for processes that are direct children
 146      *         of the process
 147      * @throws SecurityException if a security manager has been installed and
 148      *         it denies RuntimePermission("manageProcess")
 149      */
 150     Stream<ProcessHandle> children();
 151 
 152     /**
 153      * Returns a snapshot of the current direct and indirect children of the process.
 154      * A process that is {@link #isAlive not alive} has zero children.
 155      * <p>
 156      * <em>Note that processes are created and terminate asynchronously.
 157      * There is no guarantee that a process is {@link #isAlive alive}.
 158      * </em>
 159      *
 160      * @return a Stream of ProcessHandles for processes that are direct and
 161      *         indirect children of the process
 162      * @throws SecurityException if a security manager has been installed and
 163      *         it denies RuntimePermission("manageProcess")
 164      */
 165     Stream<ProcessHandle> allChildren();
 166 
 167     /**
 168      * Returns a snapshot of all processes visible to the current process.
 169      * <p>
 170      * <em>Note that processes are created and terminate asynchronously. There
 171      * is no guarantee that a process in the stream is alive or that no other
 172      * processes may have been created since the inception of the snapshot.
 173      * </em>
 174      *
 175      * @return a Stream of ProcessHandles for all processes
 176      * @throws SecurityException if a security manager has been installed and
 177      *         it denies RuntimePermission("manageProcess")
 178      * @throws UnsupportedOperationException if the implementation
 179      *         does not support this operation
 180      */
 181     static Stream<ProcessHandle> allProcesses() {
 182         return ProcessHandleImpl.children(0);
 183     }
 184 
 185     /**
 186      * Returns a snapshot of information about the process.
 187      *
 188      * <p> An {@code Info} instance has various accessor methods that return
 189      * information about the process, if the process is alive and the
 190      * information is available.
 191      *
 192      * @return a snapshot of information about the process, always non-null
 193      */
 194     Info info();
 195 
 196     /**
 197      * Information snapshot about the process.
 198      * The attributes of a process vary by operating system and are not available
 199      * in all implementations.  Information about processes is limited
 200      * by the operating system privileges of the process making the request.
 201      * The return types are {@code Optional<T>} allowing explicit tests
 202      * and actions if the value is available.
 203      * @since 1.9
 204      */
 205     public interface Info {
 206         /**
 207          * Returns the executable pathname of the process.
 208          *
 209          * @return an {@code Optional<String>} of the executable pathname
 210          *         of the process
 211          */
 212         public Optional<String> command();
 213 
 214         /**
 215          * Returns an array of Strings of the arguments of the process.
 216          *
 217          * @return an {@code Optional<String[]>} of the arguments of the process
 218          */
 219         public Optional<String[]> arguments();
 220 
 221         /**
 222          * Returns the start time of the process.
 223          *
 224          * @return an {@code Optional<Instant>} of the start time of the process
 225          */
 226         public Optional<Instant> startInstant();
 227 
 228         /**
 229          * Returns the total cputime accumulated of the process.
 230          *
 231          * @return an {@code Optional<Duration>} for the accumulated total cputime
 232          */
 233         public Optional<Duration> totalCpuDuration();
 234 
 235         /**
 236          * Return the user of the process.
 237          *
 238          * @return an {@code Optional<String>} for the user of the process
 239          */
 240         public Optional<String> user();
 241     }
 242 
 243     /**
 244      * Returns a {@code CompletableFuture<ProcessHandle>} for the termination
 245      * of the process.
 246      * The {@link java.util.concurrent.CompletableFuture} provides the ability
 247      * to trigger dependent functions or actions that may be run synchronously
 248      * or asynchronously upon process termination.
 249      * When the process terminates the CompletableFuture is
 250      * {@link java.util.concurrent.CompletableFuture#complete completed} regardless
 251      * of the exit status of the process.
 252      * The {@code onExit} method can be called multiple times to invoke
 253      * independent actions when the process exits.
 254      * <p>
 255      * Calling {@code onExit().get()} waits for the process to terminate and returns
 256      * the ProcessHandle. The future can be used to check if the process is
 257      * {@link java.util.concurrent.CompletableFuture#isDone done} or to
 258      * {@link java.util.concurrent.Future#get() wait} for it to terminate.
 259      * {@link java.util.concurrent.Future#cancel(boolean) Cancelling}
 260      * the CompleteableFuture does not affect the Process.
 261      * <p>
 262      * If the process is {@link #isAlive not alive} the {@link CompletableFuture}
 263      * returned has been {@link java.util.concurrent.CompletableFuture#complete completed}.
 264      *
 265      * @return a new {@code CompletableFuture<ProcessHandle>} for the ProcessHandle
 266      *
 267      * @throws IllegalStateException if the process is the current process
 268      */
 269     CompletableFuture<ProcessHandle> onExit();
 270 
 271     /**
 272      * Returns {@code true} if the implementation of {@link #destroy}
 273      * normally terminates the process.
 274      * Returns {@code false} if the implementation of {@code destroy}
 275      * forcibly and immediately terminates the process.
 276      *
 277      * @return {@code true} if the implementation of {@link #destroy}
 278      *         normally terminates the process;
 279      *         otherwise, {@link #destroy} forcibly terminates the process
 280      */
 281     boolean supportsNormalTermination();
 282 
 283     /**
 284      * Requests the process to be killed.
 285      * Whether the process represented by this {@code ProcessHandle} object is
 286      * {@link #supportsNormalTermination normally terminated} or not is
 287      * implementation dependent.
 288      * Forcible process destruction is defined as the immediate termination of the
 289      * process, whereas normal termination allows the process to shut down cleanly.
 290      * If the process is not alive, no action is taken.
 291      * The operating system access controls may prevent the process
 292      * from being killed.
 293      * <p>
 294      * The {@link java.util.concurrent.CompletableFuture} from {@link #onExit} is
 295      * {@link java.util.concurrent.CompletableFuture#complete completed}
 296      * when the process has terminated.
 297      * <p>
 298      * Note: The process may not terminate immediately.
 299      * For example, {@code isAlive()} may return true for a brief period
 300      * after {@code destroy()} is called.
 301      *
 302      * @return {@code true} if termination was successfully requested,
 303      *         otherwise {@code false}
 304      * @throws IllegalStateException if the process is the current process
 305      */
 306     boolean destroy();
 307 
 308     /**
 309      * Requests the process to be killed forcibly.
 310      * The process represented by this {@code ProcessHandle} object is
 311      * forcibly terminated.
 312      * Forcible process destruction is defined as the immediate termination of the
 313      * process, whereas normal termination allows the process to shut down cleanly.
 314      * If the process is not alive, no action is taken.
 315      * The operating system access controls may prevent the process
 316      * from being killed.
 317      * <p>
 318      * The {@link java.util.concurrent.CompletableFuture} from {@link #onExit} is
 319      * {@link java.util.concurrent.CompletableFuture#complete completed}
 320      * when the process has terminated.
 321      * <p>
 322      * Note: The process may not terminate immediately.
 323      * For example, {@code isAlive()} may return true for a brief period
 324      * after {@code destroyForcibly()} is called.
 325      *
 326      * @return {@code true} if termination was successfully requested,
 327      *         otherwise {@code false}
 328      * @throws IllegalStateException if the process is the current process
 329      */
 330     boolean destroyForcibly();
 331 
 332     /**
 333      * Tests whether the process represented by this {@code ProcessHandle} is alive.
 334      * Process termination is implementation and operating system specific.
 335      * The process is considered alive as long as the PID is valid.
 336      *
 337      * @return {@code true} if the process represented by this
 338      *         {@code ProcessHandle} object has not yet terminated
 339      */
 340    boolean isAlive();
 341 
 342     /**
 343      * Compares this ProcessHandle with the specified ProcessHandle for order.
 344      * The order is not specified, but is consistent with {@link Object#equals},
 345      * which returns {@code true} if and only if two instances of ProcessHandle
 346      * are of the same implementation and represent the same system process.
 347      * Comparison is only supported among objects of same implementation.
 348      * If attempt is made to mutually compare two different implementations
 349      * of {@link ProcessHandle}s, {@link ClassCastException} is thrown.
 350      *
 351      * @param other the ProcessHandle to be compared
 352      * @return a negative integer, zero, or a positive integer as this object
 353      * is less than, equal to, or greater than the specified object.
 354      * @throws NullPointerException if the specified object is null
 355      * @throws ClassCastException if the specified object is not of same class
 356      *         as this object
 357      */
 358     @Override
 359     int compareTo(ProcessHandle other);
 360 
 361 }