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  * <p>
  82  * The {@code ProcessHandle} static factory methods return instances that are
  83  * <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>,
  84  * immutable and thread-safe.
  85  * Use of identity-sensitive operations (including reference equality
  86  * ({@code ==}), identity hash code, or synchronization) on these instances of
  87  * {@code ProcessHandle} may have unpredictable results and should be avoided.
  88  * Use {@link #equals(Object) equals} or
  89  * {@link #compareTo(ProcessHandle) compareTo} methods to compare ProcessHandles.
  90  *
  91  * @see Process
  92  * @since 1.9
  93  */
  94 public interface ProcessHandle extends Comparable<ProcessHandle> {
  95 
  96     /**
  97      * Returns the native process ID of the process. The native process ID is an
  98      * identification number that the operating system assigns to the process.
  99      * The operating system may reuse the process ID after a process terminates.
 100      * Use {@link #equals(Object) equals} or
 101      * {@link #compareTo(ProcessHandle) compareTo} to compare ProcessHandles.
 102      *
 103      * @return the native process ID of the process
 104      * @throws UnsupportedOperationException if the implementation
 105      *         does not support this operation
 106      */
 107     long getPid();
 108 
 109     /**
 110      * Returns an {@code Optional<ProcessHandle>} for an existing native process.
 111      *
 112      * @param pid a native process ID
 113      * @return an {@code Optional<ProcessHandle>} of the PID for the process;
 114      *         the {@code Optional} is empty if the process does not exist
 115      * @throws SecurityException if a security manager has been installed and
 116      *         it denies RuntimePermission("manageProcess")
 117      * @throws UnsupportedOperationException if the implementation
 118      *         does not support this operation
 119      */
 120     public static Optional<ProcessHandle> of(long pid) {
 121         return ProcessHandleImpl.get(pid);
 122     }
 123 
 124     /**
 125      * Returns a ProcessHandle for the current process. The ProcessHandle cannot be
 126      * used to destroy the current process, use {@link System#exit System.exit} instead.
 127      *
 128      * @return a ProcessHandle for the current process
 129      * @throws SecurityException if a security manager has been installed and
 130      *         it denies RuntimePermission("manageProcess")
 131      * @throws UnsupportedOperationException if the implementation
 132      *         does not support this operation
 133      */
 134     public static ProcessHandle current() {
 135         return ProcessHandleImpl.current();
 136     }
 137 
 138     /**
 139      * Returns an {@code Optional<ProcessHandle>} for the parent process.
 140      * Note that Processes in a zombie state usually don't have a parent.
 141      *
 142      * @return an {@code Optional<ProcessHandle>} of the parent process;
 143      *         the {@code Optional} is empty if the child process does not have a parent
 144      *         or if the parent is not available, possibly due to operating system limitations
 145      * @throws SecurityException if a security manager has been installed and
 146      *         it denies RuntimePermission("manageProcess")
 147      */
 148     Optional<ProcessHandle> parent();
 149 
 150     /**
 151      * Returns a snapshot of the current direct children of the process.
 152      * A process that is {@link #isAlive not alive} has zero children.
 153      * <p>
 154      * <em>Note that processes are created and terminate asynchronously.
 155      * There is no guarantee that a process is {@link #isAlive alive}.
 156      * </em>
 157      *
 158      * @return a Stream of ProcessHandles for processes that are direct children
 159      *         of the process
 160      * @throws SecurityException if a security manager has been installed and
 161      *         it denies RuntimePermission("manageProcess")
 162      */
 163     Stream<ProcessHandle> children();
 164 
 165     /**
 166      * Returns a snapshot of the current direct and indirect children of the process.
 167      * A process that is {@link #isAlive not alive} has zero children.
 168      * <p>
 169      * <em>Note that processes are created and terminate asynchronously.
 170      * There is no guarantee that a process is {@link #isAlive alive}.
 171      * </em>
 172      *
 173      * @return a Stream of ProcessHandles for processes that are direct and
 174      *         indirect children of the process
 175      * @throws SecurityException if a security manager has been installed and
 176      *         it denies RuntimePermission("manageProcess")
 177      */
 178     Stream<ProcessHandle> allChildren();
 179 
 180     /**
 181      * Returns a snapshot of all processes visible to the current process.
 182      * <p>
 183      * <em>Note that processes are created and terminate asynchronously. There
 184      * is no guarantee that a process in the stream is alive or that no other
 185      * processes may have been created since the inception of the snapshot.
 186      * </em>
 187      *
 188      * @return a Stream of ProcessHandles for all processes
 189      * @throws SecurityException if a security manager has been installed and
 190      *         it denies RuntimePermission("manageProcess")
 191      * @throws UnsupportedOperationException if the implementation
 192      *         does not support this operation
 193      */
 194     static Stream<ProcessHandle> allProcesses() {
 195         return ProcessHandleImpl.children(0);
 196     }
 197 
 198     /**
 199      * Returns a snapshot of information about the process.
 200      *
 201      * <p> An {@code Info} instance has various accessor methods that return
 202      * information about the process, if the process is alive and the
 203      * information is available.
 204      *
 205      * @return a snapshot of information about the process, always non-null
 206      */
 207     Info info();
 208 
 209     /**
 210      * Information snapshot about the process.
 211      * The attributes of a process vary by operating system and are not available
 212      * in all implementations.  Information about processes is limited
 213      * by the operating system privileges of the process making the request.
 214      * The return types are {@code Optional<T>} allowing explicit tests
 215      * and actions if the value is available.
 216      * @since 1.9
 217      */
 218     public interface Info {
 219         /**
 220          * Returns the executable pathname of the process.
 221          *
 222          * @return an {@code Optional<String>} of the executable pathname
 223          *         of the process
 224          */
 225         public Optional<String> command();
 226 
 227         /**
 228          * Returns the command line of the process.
 229          * <p>
 230          * If {@link #command command()} and  {@link #arguments arguments()} return
 231          * non-empty optionals, this is simply a convenience method which concatenates
 232          * the values of the two functions separated by spaces. Otherwise it will return a
 233          * best-effort, platform dependent representation of the command line.
 234          *
 235          * @apiNote Note that the returned executable pathname and the
 236          *          arguments may be truncated on some platforms due to system
 237          *          limitations.
 238          *          <p>
 239          *          The executable pathname may contain only the
 240          *          name of the executable without the full path information.
 241          *          It is undecideable whether white space separates different
 242          *          arguments or is part of a single argument.
 243          *
 244          * @return an {@code Optional<String>} of the command line
 245          *         of the process
 246          */
 247         public Optional<String> commandLine();
 248 
 249         /**
 250          * Returns an array of Strings of the arguments of the process.
 251          *
 252          * @apiNote On some platforms, native applications are free to change
 253          *          the arguments array after startup and this method may only
 254          *          show the changed values.
 255          *
 256          * @return an {@code Optional<String[]>} of the arguments of the process
 257          */
 258         public Optional<String[]> arguments();
 259 
 260         /**
 261          * Returns the start time of the process.
 262          *
 263          * @return an {@code Optional<Instant>} of the start time of the process
 264          */
 265         public Optional<Instant> startInstant();
 266 
 267         /**
 268          * Returns the total cputime accumulated of the process.
 269          *
 270          * @return an {@code Optional<Duration>} for the accumulated total cputime
 271          */
 272         public Optional<Duration> totalCpuDuration();
 273 
 274         /**
 275          * Return the user of the process.
 276          *
 277          * @return an {@code Optional<String>} for the user of the process
 278          */
 279         public Optional<String> user();
 280     }
 281 
 282     /**
 283      * Returns a {@code CompletableFuture<ProcessHandle>} for the termination
 284      * of the process.
 285      * The {@link java.util.concurrent.CompletableFuture} provides the ability
 286      * to trigger dependent functions or actions that may be run synchronously
 287      * or asynchronously upon process termination.
 288      * When the process terminates the CompletableFuture is
 289      * {@link java.util.concurrent.CompletableFuture#complete completed} regardless
 290      * of the exit status of the process.
 291      * The {@code onExit} method can be called multiple times to invoke
 292      * independent actions when the process exits.
 293      * <p>
 294      * Calling {@code onExit().get()} waits for the process to terminate and returns
 295      * the ProcessHandle. The future can be used to check if the process is
 296      * {@link java.util.concurrent.CompletableFuture#isDone done} or to
 297      * {@link java.util.concurrent.Future#get() wait} for it to terminate.
 298      * {@link java.util.concurrent.Future#cancel(boolean) Cancelling}
 299      * the CompleteableFuture does not affect the Process.
 300      * <p>
 301      * If the process is {@link #isAlive not alive} the {@link CompletableFuture}
 302      * returned has been {@link java.util.concurrent.CompletableFuture#complete completed}.
 303      *
 304      * @return a new {@code CompletableFuture<ProcessHandle>} for the ProcessHandle
 305      *
 306      * @throws IllegalStateException if the process is the current process
 307      */
 308     CompletableFuture<ProcessHandle> onExit();
 309 
 310     /**
 311      * Returns {@code true} if the implementation of {@link #destroy}
 312      * normally terminates the process.
 313      * Returns {@code false} if the implementation of {@code destroy}
 314      * forcibly and immediately terminates the process.
 315      *
 316      * @return {@code true} if the implementation of {@link #destroy}
 317      *         normally terminates the process;
 318      *         otherwise, {@link #destroy} forcibly terminates the process
 319      */
 320     boolean supportsNormalTermination();
 321 
 322     /**
 323      * Requests the process to be killed.
 324      * Whether the process represented by this {@code ProcessHandle} object is
 325      * {@link #supportsNormalTermination normally terminated} or not is
 326      * implementation dependent.
 327      * Forcible process destruction is defined as the immediate termination of the
 328      * process, whereas normal termination allows the process to shut down cleanly.
 329      * If the process is not alive, no action is taken.
 330      * The operating system access controls may prevent the process
 331      * from being killed.
 332      * <p>
 333      * The {@link java.util.concurrent.CompletableFuture} from {@link #onExit} is
 334      * {@link java.util.concurrent.CompletableFuture#complete completed}
 335      * when the process has terminated.
 336      * <p>
 337      * Note: The process may not terminate immediately.
 338      * For example, {@code isAlive()} may return true for a brief period
 339      * after {@code destroy()} is called.
 340      *
 341      * @return {@code true} if termination was successfully requested,
 342      *         otherwise {@code false}
 343      * @throws IllegalStateException if the process is the current process
 344      */
 345     boolean destroy();
 346 
 347     /**
 348      * Requests the process to be killed forcibly.
 349      * The process represented by this {@code ProcessHandle} object is
 350      * forcibly terminated.
 351      * Forcible process destruction is defined as the immediate termination of the
 352      * process, whereas normal termination allows the process to shut down cleanly.
 353      * If the process is not alive, no action is taken.
 354      * The operating system access controls may prevent the process
 355      * from being killed.
 356      * <p>
 357      * The {@link java.util.concurrent.CompletableFuture} from {@link #onExit} is
 358      * {@link java.util.concurrent.CompletableFuture#complete completed}
 359      * when the process has terminated.
 360      * <p>
 361      * Note: The process may not terminate immediately.
 362      * For example, {@code isAlive()} may return true for a brief period
 363      * after {@code destroyForcibly()} is called.
 364      *
 365      * @return {@code true} if termination was successfully requested,
 366      *         otherwise {@code false}
 367      * @throws IllegalStateException if the process is the current process
 368      */
 369     boolean destroyForcibly();
 370 
 371     /**
 372      * Tests whether the process represented by this {@code ProcessHandle} is alive.
 373      * Process termination is implementation and operating system specific.
 374      * The process is considered alive as long as the PID is valid.
 375      *
 376      * @return {@code true} if the process represented by this
 377      *         {@code ProcessHandle} object has not yet terminated
 378      */
 379     boolean isAlive();
 380 
 381     /**
 382      * Returns a hash code value for this ProcessHandle.
 383      * The hashcode value follows the general contract for {@link Object#hashCode()}.
 384      * The value is a function of the {@link #getPid getPid()} value and
 385      * may be a function of additional information to uniquely identify the process.
 386      * If two ProcessHandles are equal according to the {@link #equals(Object) equals}
 387      * method, then calling the hashCode method on each of the two objects
 388      * must produce the same integer result.
 389      *
 390      * @return a hash code value for this object
 391      */
 392     @Override
 393     int hashCode();
 394 
 395     /**
 396      * Returns {@code true} if {@code other} object is non-null, is of the
 397      * same implementation, and represents the same system process;
 398      * otherwise it returns {@code false}.
 399      * @implNote
 400      * It is implementation specific whether ProcessHandles with the same PID
 401      * represent the same system process. ProcessHandle implementations
 402      * should contain additional information to uniquely identify the process.
 403      * For example, the start time of the process could be used
 404      * to determine if the PID has been re-used.
 405      * The implementation of {@code equals} should return {@code true} for two
 406      * ProcessHandles with the same PID unless there is information to
 407      * distinguish them.
 408      *
 409      * @param other another object
 410      * @return {@code true} if the {@code other} object is non-null,
 411      *         is of the same implementation class and represents
 412      *         the same system process; otherwise returns {@code false}
 413      */
 414     @Override
 415     boolean equals(Object other);
 416 
 417     /**
 418      * Compares this ProcessHandle with the specified ProcessHandle for order.
 419      * The order is not specified, but is consistent with {@link Object#equals},
 420      * which returns {@code true} if and only if two instances of ProcessHandle
 421      * are of the same implementation and represent the same system process.
 422      * Comparison is only supported among objects of same implementation.
 423      * If attempt is made to mutually compare two different implementations
 424      * of {@link ProcessHandle}s, {@link ClassCastException} is thrown.
 425      *
 426      * @param other the ProcessHandle to be compared
 427      * @return a negative integer, zero, or a positive integer as this object
 428      * is less than, equal to, or greater than the specified object.
 429      * @throws NullPointerException if the specified object is null
 430      * @throws ClassCastException if the specified object is not of same class
 431      *         as this object
 432      */
 433     @Override
 434     int compareTo(ProcessHandle other);
 435 
 436 }