1 /*
   2  * Copyright (c) 1995, 2012, 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 
  26 package java.lang;
  27 
  28 import java.io.*;
  29 import java.util.concurrent.TimeUnit;
  30 
  31 /**
  32  * The {@link ProcessBuilder#start()} and
  33  * {@link Runtime#exec(String[],String[],File) Runtime.exec}
  34  * methods create a native process and return an instance of a
  35  * subclass of {@code Process} that can be used to control the process
  36  * and obtain information about it.  The class {@code Process}
  37  * provides methods for performing input from the process, performing
  38  * output to the process, waiting for the process to complete,
  39  * checking the exit status of the process, and destroying (killing)
  40  * the process.
  41  *
  42  * <p>The methods that create processes may not work well for special
  43  * processes on certain native platforms, such as native windowing
  44  * processes, daemon processes, Win16/DOS processes on Microsoft
  45  * Windows, or shell scripts.
  46  *
  47  * <p>By default, the created subprocess does not have its own terminal
  48  * or console.  All its standard I/O (i.e. stdin, stdout, stderr)
  49  * operations will be redirected to the parent process, where they can
  50  * be accessed via the streams obtained using the methods
  51  * {@link #getOutputStream()},
  52  * {@link #getInputStream()}, and
  53  * {@link #getErrorStream()}.
  54  * The parent process uses these streams to feed input to and get output
  55  * from the subprocess.  Because some native platforms only provide
  56  * limited buffer size for standard input and output streams, failure
  57  * to promptly write the input stream or read the output stream of
  58  * the subprocess may cause the subprocess to block, or even deadlock.
  59  *
  60  * <p>Where desired, <a href="ProcessBuilder.html#redirect-input">
  61  * subprocess I/O can also be redirected</a>
  62  * using methods of the {@link ProcessBuilder} class.
  63  *
  64  * <p>The subprocess is not killed when there are no more references to
  65  * the {@code Process} object, but rather the subprocess
  66  * continues executing asynchronously.
  67  *
  68  * <p>There is no requirement that a process represented by a {@code
  69  * Process} object execute asynchronously or concurrently with respect
  70  * to the Java process that owns the {@code Process} object.
  71  *
  72  * <p>As of 1.5, {@link ProcessBuilder#start()} is the preferred way
  73  * to create a {@code Process}.
  74  *
  75  * @since   JDK1.0
  76  */
  77 public abstract class Process {
  78     /**
  79      * Returns the output stream connected to the normal input of the
  80      * subprocess.  Output to the stream is piped into the standard
  81      * input of the process represented by this {@code Process} object.
  82      *
  83      * <p>If the standard input of the subprocess has been redirected using
  84      * {@link ProcessBuilder#redirectInput(Redirect)
  85      * ProcessBuilder.redirectInput}
  86      * then this method will return a
  87      * <a href="ProcessBuilder.html#redirect-input">null output stream</a>.
  88      *
  89      * <p>Implementation note: It is a good idea for the returned
  90      * output stream to be buffered.
  91      *
  92      * @return the output stream connected to the normal input of the
  93      *         subprocess
  94      */
  95     public abstract OutputStream getOutputStream();
  96 
  97     /**
  98      * Returns the input stream connected to the normal output of the
  99      * subprocess.  The stream obtains data piped from the standard
 100      * output of the process represented by this {@code Process} object.
 101      *
 102      * <p>If the standard output of the subprocess has been redirected using
 103      * {@link ProcessBuilder#redirectOutput(Redirect)
 104      * ProcessBuilder.redirectOutput}
 105      * then this method will return a
 106      * <a href="ProcessBuilder.html#redirect-output">null input stream</a>.
 107      *
 108      * <p>Otherwise, if the standard error of the subprocess has been
 109      * redirected using
 110      * {@link ProcessBuilder#redirectErrorStream(boolean)
 111      * ProcessBuilder.redirectErrorStream}
 112      * then the input stream returned by this method will receive the
 113      * merged standard output and the standard error of the subprocess.
 114      *
 115      * <p>Implementation note: It is a good idea for the returned
 116      * input stream to be buffered.
 117      *
 118      * @return the input stream connected to the normal output of the
 119      *         subprocess
 120      */
 121     public abstract InputStream getInputStream();
 122 
 123     /**
 124      * Returns the input stream connected to the error output of the
 125      * subprocess.  The stream obtains data piped from the error output
 126      * of the process represented by this {@code Process} object.
 127      *
 128      * <p>If the standard error of the subprocess has been redirected using
 129      * {@link ProcessBuilder#redirectError(Redirect)
 130      * ProcessBuilder.redirectError} or
 131      * {@link ProcessBuilder#redirectErrorStream(boolean)
 132      * ProcessBuilder.redirectErrorStream}
 133      * then this method will return a
 134      * <a href="ProcessBuilder.html#redirect-output">null input stream</a>.
 135      *
 136      * <p>Implementation note: It is a good idea for the returned
 137      * input stream to be buffered.
 138      *
 139      * @return the input stream connected to the error output of
 140      *         the subprocess
 141      */
 142     public abstract InputStream getErrorStream();
 143 
 144     /**
 145      * Causes the current thread to wait, if necessary, until the
 146      * process represented by this {@code Process} object has
 147      * terminated.  This method returns immediately if the subprocess
 148      * has already terminated.  If the subprocess has not yet
 149      * terminated, the calling thread will be blocked until the
 150      * subprocess exits.
 151      *
 152      * @return the exit value of the subprocess represented by this
 153      *         {@code Process} object.  By convention, the value
 154      *         {@code 0} indicates normal termination.
 155      * @throws InterruptedException if the current thread is
 156      *         {@linkplain Thread#interrupt() interrupted} by another
 157      *         thread while it is waiting, then the wait is ended and
 158      *         an {@link InterruptedException} is thrown.
 159      */
 160     public abstract int waitFor() throws InterruptedException;
 161         
 162     /**
 163      * Causes the current thread to wait until the subprocess represented by 
 164      * this {@code Process} has terminated, unless the thread is 
 165      * {@linkplain Thread#interrupt interrupted}, or the specified waiting time
 166      * elapses.
 167      *
 168      * <p>If the subprocess has already exited then this method returns 
 169      * immediately with the value {@code true}.  If the process has not exited
 170      * and the timeout is zero then this method returns immediately with the
 171      * value {@code false}
 172      *
 173      * <p>If the subprocess has not exited then the current
 174      * thread becomes disabled for thread scheduling purposes and lies
 175      * dormant until one of three things happen:
 176      * <ul>
 177      * <li>The subprocess exits; or
 178      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 179      * the current thread; or
 180      * <li>The specified waiting time elapses.
 181      * </ul>
 182      *
 183      * <p>If the subprocess terminates then the method returns with the
 184      * value {@code true}.
 185      * 
 186      * <p>If the current thread:
 187      * <ul>
 188      * <li>has its interrupted status set on entry to this method; or
 189      * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
 190      * </ul>
 191      * then {@link InterruptedException} is thrown and the current thread's
 192      * interrupted status is cleared.
 193      *
 194      * <p>If the specified waiting time elapses and the subprocess has not 
 195      * exited then the value {@code false} is returned.  If the time is less 
 196      * than or equal to zero, the method will not wait at all.
 197      *
 198      * <p>The default implementation of this method polls {@code exitValue()} 
 199      * and repeatedly catches the resulting {@code IllegalThreadStateException} 
 200      * until the {@code timeout} expires or the subprocess is terminated.
 201      * Implementations are strongly encouraged to override this method.
 202      *
 203      * @param timeout the maximum time to wait
 204      * @param unit the time unit of the {@code timeout} argument
 205      * @return {@code true} if the subprocess has exited and {@code false} if
 206      *         the waiting time elapsed before the subprocess has exited.
 207      * @throws InterruptedException if the current thread is interrupted
 208      *         while waiting
 209      * @since 1.8
 210      */
 211     public boolean waitFor(long timeout, TimeUnit unit) 
 212         throws InterruptedException {
 213         long now = System.nanoTime();
 214 
 215         long end = now + TimeUnit.NANOSECONDS.convert(timeout, unit);
 216         if (end <= 0) // overflow
 217             end = Long.MAX_VALUE;
 218 
 219         long rem = end - now;
 220         do {
 221             try {
 222                 exitValue();
 223                 return true;
 224             } catch(IllegalThreadStateException ex) {
 225                 if(rem > 0) Thread.sleep(rem < 100 ? rem : 100);
 226             }
 227             rem = end - System.nanoTime();
 228         } while(rem > 0);
 229         return false;
 230     }
 231 
 232     /**
 233      * Returns the exit value for the subprocess.
 234      *
 235      * @return the exit value of the subprocess represented by this
 236      *         {@code Process} object.  By convention, the value
 237      *         {@code 0} indicates normal termination.
 238      * @throws IllegalThreadStateException if the subprocess represented
 239      *         by this {@code Process} object has not yet terminated
 240      */
 241     public abstract int exitValue();
 242 
 243     /**
 244      * Kills the subprocess. Whether the subprocess represented by this
 245      * {@code Process} object is forcibly terminated or not is 
 246      * implementation dependent.
 247      */
 248     public abstract void destroy();
 249 
 250     /**
 251      * Kills the subprocess. The subprocess represented by this
 252      * {@code Process} object is forcibly terminated.
 253      * 
 254      * <p>The default implementation of this method invokes {@link #destroy()} 
 255      * and so is implementation dependent as to whether it terminates the 
 256      * process forcibly or not.  Implementations are strongly encouraged to 
 257      * override this method.
 258      *
 259      * <p>Note: The subprocess may not terminate immediately. 
 260      * i.e. {@code isAlive()} may return true for a brief period
 261      * after {@code destroyForcibly()} is called, however this method
 262      * may be chained to {@code waitFor()} if needed.
 263      *
 264      * @return the {@code Process} object representing the
 265      *         subprocess to be forcibly destroyed.
 266      * @since 1.8
 267      */
 268     public Process destroyForcibly() {
 269         destroy();
 270         return this;
 271     }
 272 
 273     /**
 274      * Tests whether the subprocess represented by this {@code Process} is 
 275      * alive.
 276      *
 277      * @return {@code true} if the subprocess represented by this
 278      *         {@code Process} object has not yet terminated.
 279      * @since 1.8
 280      */
 281     public boolean isAlive() {
 282         try {
 283             exitValue();
 284             return false;
 285         } catch(IllegalThreadStateException e) {
 286             return true;
 287         }
 288     }
 289 }