1/* 2 * Copyright (c) 1995, 2017, 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 26package java.lang; 27 28import java.io.*; 29import java.lang.ProcessBuilder.Redirect; 30import java.util.concurrent.CompletableFuture; 31import java.util.concurrent.ForkJoinPool; 32import java.util.concurrent.TimeUnit; 33import java.util.stream.Stream; 34 35/** 36 * {@code Process} provides control of native processes started by 37 * ProcessBuilder.start and Runtime.exec. 38 * The class provides methods for performing input from the process, performing 39 * output to the process, waiting for the process to complete, 40 * checking the exit status of the process, and destroying (killing) 41 * the process. 42 * The {@link ProcessBuilder#start()} and 43 * {@link Runtime#exec(String[],String[],File) Runtime.exec} 44 * methods create a native process and return an instance of a 45 * subclass of {@code Process} that can be used to control the process 46 * and obtain information about it. 47 * 48 * <p>The methods that create processes may not work well for special 49 * processes on certain native platforms, such as native windowing 50 * processes, daemon processes, Win16/DOS processes on Microsoft 51 * Windows, or shell scripts. 52 * 53 * <p>By default, the created process does not have its own terminal 54 * or console. All its standard I/O (i.e. stdin, stdout, stderr) 55 * operations will be redirected to the parent process, where they can 56 * be accessed via the streams obtained using the methods 57 * {@link #getOutputStream()}, 58 * {@link #getInputStream()}, and 59 * {@link #getErrorStream()}. 60 * The parent process uses these streams to feed input to and get output 61 * from the process. Because some native platforms only provide 62 * limited buffer size for standard input and output streams, failure 63 * to promptly write the input stream or read the output stream of 64 * the process may cause the process to block, or even deadlock. 65 * 66 * <p>Where desired, <a href="ProcessBuilder.html#redirect-input"> 67 * process I/O can also be redirected</a> 68 * using methods of the {@link ProcessBuilder} class. 69 * 70 * <p>The process is not killed when there are no more references to 71 * the {@code Process} object, but rather the process 72 * continues executing asynchronously. 73 * 74 * <p>There is no requirement that the process represented by a {@code 75 * Process} object execute asynchronously or concurrently with respect 76 * to the Java process that owns the {@code Process} object. 77 * 78 * <p>As of 1.5, {@link ProcessBuilder#start()} is the preferred way 79 * to create a {@code Process}. 80 * 81 * <p>Subclasses of Process should override the {@link #onExit()} and 82 * {@link #toHandle()} methods to provide a fully functional Process including the 83 * {@linkplain #pid() process id}, 84 * {@linkplain #info() information about the process}, 85 * {@linkplain #children() direct children}, and 86 * {@linkplain #descendants() direct children plus descendants of those children} of the process. 87 * Delegating to the underlying Process or ProcessHandle is typically 88 * easiest and most efficient. 89 * 90 * @since 1.0 91 */ 92public abstract class Process { 93 /** 94 * Default constructor for Process. 95 */ 96 public Process() {} 97 98 /** 99 * Returns the output stream connected to the normal input of the 100 * process. Output to the stream is piped into the standard 101 * input of the process represented by this {@code Process} object. 102 * 103 * <p>If the standard input of the process has been redirected using 104 * {@link ProcessBuilder#redirectInput(Redirect) 105 * ProcessBuilder.redirectInput} 106 * then this method will return a 107 * <a href="ProcessBuilder.html#redirect-input">null output stream</a>. 108 * 109 * <p>Implementation note: It is a good idea for the returned 110 * output stream to be buffered. 111 * 112 * @return the output stream connected to the normal input of the 113 * process 114 */ 115 public abstract OutputStream getOutputStream(); 116 117 /** 118 * Returns the input stream connected to the normal output of the 119 * process. The stream obtains data piped from the standard 120 * output of the process represented by this {@code Process} object. 121 * 122 * <p>If the standard output of the process has been redirected using 123 * {@link ProcessBuilder#redirectOutput(Redirect) 124 * ProcessBuilder.redirectOutput} 125 * then this method will return a 126 * <a href="ProcessBuilder.html#redirect-output">null input stream</a>. 127 * 128 * <p>Otherwise, if the standard error of the process has been 129 * redirected using 130 * {@link ProcessBuilder#redirectErrorStream(boolean) 131 * ProcessBuilder.redirectErrorStream} 132 * then the input stream returned by this method will receive the 133 * merged standard output and the standard error of the process. 134 * 135 * <p>Implementation note: It is a good idea for the returned 136 * input stream to be buffered. 137 * 138 * @return the input stream connected to the normal output of the 139 * process 140 */ 141 public abstract InputStream getInputStream(); 142 143 /** 144 * Returns the input stream connected to the error output of the 145 * process. The stream obtains data piped from the error output 146 * of the process represented by this {@code Process} object. 147 * 148 * <p>If the standard error of the process has been redirected using 149 * {@link ProcessBuilder#redirectError(Redirect) 150 * ProcessBuilder.redirectError} or 151 * {@link ProcessBuilder#redirectErrorStream(boolean) 152 * ProcessBuilder.redirectErrorStream} 153 * then this method will return a 154 * <a href="ProcessBuilder.html#redirect-output">null input stream</a>. 155 * 156 * <p>Implementation note: It is a good idea for the returned 157 * input stream to be buffered. 158 * 159 * @return the input stream connected to the error output of 160 * the process 161 */ 162 public abstract InputStream getErrorStream(); 163 164 /** 165 * Causes the current thread to wait, if necessary, until the 166 * process represented by this {@code Process} object has 167 * terminated. This method returns immediately if the process 168 * has already terminated. If the process has not yet 169 * terminated, the calling thread will be blocked until the 170 * process exits. 171 * 172 * @return the exit value of the process represented by this 173 * {@code Process} object. By convention, the value 174 * {@code 0} indicates normal termination. 175 * @throws InterruptedException if the current thread is 176 * {@linkplain Thread#interrupt() interrupted} by another 177 * thread while it is waiting, then the wait is ended and 178 * an {@link InterruptedException} is thrown. 179 */ 180 public abstract int waitFor() throws InterruptedException; 181 182 /** 183 * Causes the current thread to wait, if necessary, until the 184 * process represented by this {@code Process} object has 185 * terminated, or the specified waiting time elapses. 186 * 187 * <p>If the process has already terminated then this method returns 188 * immediately with the value {@code true}. If the process has not 189 * terminated and the timeout value is less than, or equal to, zero, then 190 * this method returns immediately with the value {@code false}. 191 * 192 * <p>The default implementation of this methods polls the {@code exitValue} 193 * to check if the process has terminated. Concrete implementations of this 194 * class are strongly encouraged to override this method with a more 195 * efficient implementation. 196 * 197 * @param timeout the maximum time to wait 198 * @param unit the time unit of the {@code timeout} argument 199 * @return {@code true} if the process has exited and {@code false} if 200 * the waiting time elapsed before the process has exited. 201 * @throws InterruptedException if the current thread is interrupted 202 * while waiting. 203 * @throws NullPointerException if unit is null 204 * @since 1.8 205 */ 206 public boolean waitFor(long timeout, TimeUnit unit) 207 throws InterruptedException 208 { 209 long startTime = System.nanoTime(); 210 long rem = unit.toNanos(timeout); 211 212 do { 213 try { 214 exitValue(); 215 return true; 216 } catch(IllegalThreadStateException ex) { 217 if (rem > 0) 218 Thread.sleep( 219 Math.min(TimeUnit.NANOSECONDS.toMillis(rem) + 1, 100)); 220 } 221 rem = unit.toNanos(timeout) - (System.nanoTime() - startTime); 222 } while (rem > 0); 223 return false; 224 } 225 226 /** 227 * Returns the exit value for the process. 228 * 229 * @return the exit value of the process represented by this 230 * {@code Process} object. By convention, the value 231 * {@code 0} indicates normal termination. 232 * @throws IllegalThreadStateException if the process represented 233 * by this {@code Process} object has not yet terminated 234 */ 235 public abstract int exitValue(); 236 237 /** 238 * Kills the process. 239 * Whether the process represented by this {@code Process} object is 240 * {@linkplain #supportsNormalTermination normally terminated} or not is 241 * implementation dependent. 242 * Forcible process destruction is defined as the immediate termination of a 243 * process, whereas normal termination allows the process to shut down cleanly. 244 * If the process is not alive, no action is taken. 245 * <p> 246 * The {@link java.util.concurrent.CompletableFuture} from {@link #onExit} is 247 * {@linkplain java.util.concurrent.CompletableFuture#complete completed} 248 * when the process has terminated. 249 */ 250 public abstract void destroy(); 251 252 /** 253 * Kills the process forcibly. The process represented by this 254 * {@code Process} object is forcibly terminated. 255 * Forcible process destruction is defined as the immediate termination of a 256 * process, whereas normal termination allows the process to shut down cleanly. 257 * If the process is not alive, no action is taken. 258 * <p> 259 * The {@link java.util.concurrent.CompletableFuture} from {@link #onExit} is 260 * {@linkplain java.util.concurrent.CompletableFuture#complete completed} 261 * when the process has terminated. 262 * <p> 263 * Invoking this method on {@code Process} objects returned by 264 * {@link ProcessBuilder#start} and {@link Runtime#exec} forcibly terminate 265 * the process. 266 * 267 * @implSpec 268 * The default implementation of this method invokes {@link #destroy} 269 * and so may not forcibly terminate the process. 270 * @implNote 271 * Concrete implementations of this class are strongly encouraged to override 272 * this method with a compliant implementation. 273 * @apiNote 274 * The process may not terminate immediately. 275 * i.e. {@code isAlive()} may return true for a brief period 276 * after {@code destroyForcibly()} is called. This method 277 * may be chained to {@code waitFor()} if needed. 278 * 279 * @return the {@code Process} object representing the 280 * process forcibly destroyed 281 * @since 1.8 282 */ 283 public Process destroyForcibly() { 284 destroy(); 285 return this; 286 } 287 288 /** 289 * Returns {@code true} if the implementation of {@link #destroy} is to 290 * normally terminate the process, 291 * Returns {@code false} if the implementation of {@code destroy} 292 * forcibly and immediately terminates the process. 293 * <p> 294 * Invoking this method on {@code Process} objects returned by 295 * {@link ProcessBuilder#start} and {@link Runtime#exec} return 296 * {@code true} or {@code false} depending on the platform implementation. 297 * 298 * @implSpec 299 * This implementation throws an instance of 300 * {@link java.lang.UnsupportedOperationException} and performs no other action. 301 * 302 * @return {@code true} if the implementation of {@link #destroy} is to 303 * normally terminate the process; 304 * otherwise, {@link #destroy} forcibly terminates the process 305 * @throws UnsupportedOperationException if the Process implementation 306 * does not support this operation 307 * @since 9 308 */ 309 public boolean supportsNormalTermination() { 310 throw new UnsupportedOperationException(this.getClass() 311 + ".supportsNormalTermination() not supported" ); 312 } 313 314 /** 315 * Tests whether the process represented by this {@code Process} is 316 * alive. 317 * 318 * @return {@code true} if the process represented by this 319 * {@code Process} object has not yet terminated. 320 * @since 1.8 321 */ 322 public boolean isAlive() { 323 try { 324 exitValue(); 325 return false; 326 } catch(IllegalThreadStateException e) { 327 return true; 328 } 329 } 330 331 /** 332 * Returns the native process ID of the process. 333 * The native process ID is an identification number that the operating 334 * system assigns to the process. 335 * 336 * @implSpec 337 * The implementation of this method returns the process id as: 338 * {@link #toHandle toHandle().pid()}. 339 * 340 * @return the native process id of the process 341 * @throws UnsupportedOperationException if the Process implementation 342 * does not support this operation 343 * @since 9 344 */ 345 public long pid() { 346 return toHandle().pid(); 347 } 348 349 /** 350 * Returns a {@code CompletableFuture<Process>} for the termination of the Process. 351 * The {@link java.util.concurrent.CompletableFuture} provides the ability 352 * to trigger dependent functions or actions that may be run synchronously 353 * or asynchronously upon process termination. 354 * When the process has terminated the CompletableFuture is 355 * {@link java.util.concurrent.CompletableFuture#complete completed} regardless 356 * of the exit status of the process. 357 * <p> 358 * Calling {@code onExit().get()} waits for the process to terminate and returns 359 * the Process. The future can be used to check if the process is 360 * {@linkplain java.util.concurrent.CompletableFuture#isDone done} or to 361 * {@linkplain java.util.concurrent.CompletableFuture#get() wait} for it to terminate. 362 * {@linkplain java.util.concurrent.CompletableFuture#cancel(boolean) Cancelling} 363 * the CompletableFuture does not affect the Process. 364 * <p> 365 * Processes returned from {@link ProcessBuilder#start} override the 366 * default implementation to provide an efficient mechanism to wait 367 * for process exit. 368 * 369 * @apiNote 370 * Using {@link #onExit() onExit} is an alternative to 371 * {@link #waitFor() waitFor} that enables both additional concurrency 372 * and convenient access to the result of the Process. 373 * Lambda expressions can be used to evaluate the result of the Process 374 * execution. 375 * If there is other processing to be done before the value is used 376 * then {@linkplain #onExit onExit} is a convenient mechanism to 377 * free the current thread and block only if and when the value is needed. 378 * <br> 379 * For example, launching a process to compare two files and get a boolean if they are identical: 380 * <pre> {@code Process p = new ProcessBuilder("cmp", "f1", "f2").start(); 381 * Future<Boolean> identical = p.onExit().thenApply(p1 -> p1.exitValue() == 0); 382 * ... 383 * if (identical.get()) { ... } 384 * }</pre> 385 * 386 * @implSpec 387 * This implementation executes {@link #waitFor()} in a separate thread 388 * repeatedly until it returns successfully. If the execution of 389 * {@code waitFor} is interrupted, the thread's interrupt status is preserved. 390 * <p> 391 * When {@link #waitFor()} returns successfully the CompletableFuture is 392 * {@linkplain java.util.concurrent.CompletableFuture#complete completed} regardless 393 * of the exit status of the process. 394 * 395 * This implementation may consume a lot of memory for thread stacks if a 396 * large number of processes are waited for concurrently. 397 * <p> 398 * External implementations should override this method and provide 399 * a more efficient implementation. For example, to delegate to the underlying 400 * process, it can do the following: 401 * <pre>{@code 402 * public CompletableFuture<Process> onExit() { 403 * return delegate.onExit().thenApply(p -> this); 404 * } 405 * }</pre> 406 * @apiNote 407 * The process may be observed to have terminated with {@link #isAlive} 408 * before the ComputableFuture is completed and dependent actions are invoked. 409 * 410 * @return a new {@code CompletableFuture<Process>} for the Process 411 * 412 * @since 9 413 */ 414 public CompletableFuture<Process> onExit() { 415 return CompletableFuture.supplyAsync(this::waitForInternal); 416 } 417 418 /** 419 * Wait for the process to exit by calling {@code waitFor}. 420 * If the thread is interrupted, remember the interrupted state to 421 * be restored before returning. Use ForkJoinPool.ManagedBlocker 422 * so that the number of workers in case ForkJoinPool is used is 423 * compensated when the thread blocks in waitFor(). 424 * 425 * @return the Process 426 */ 427 private Process waitForInternal() { 428 boolean interrupted = false; 429 while (true) { 430 try { 431 ForkJoinPool.managedBlock(new ForkJoinPool.ManagedBlocker() { 432 @Override 433 public boolean block() throws InterruptedException { 434 waitFor(); 435 return true; 436 } 437 438 @Override 439 public boolean isReleasable() { 440 return !isAlive(); 441 } 442 }); 443 break; 444 } catch (InterruptedException x) { 445 interrupted = true; 446 } 447 } 448 if (interrupted) { 449 Thread.currentThread().interrupt(); 450 } 451 return this; 452 } 453 454 /** 455 * Returns a ProcessHandle for the Process. 456 * 457 * {@code Process} objects returned by {@link ProcessBuilder#start} and 458 * {@link Runtime#exec} implement {@code toHandle} as the equivalent of 459 * {@link ProcessHandle#of(long) ProcessHandle.of(pid)} including the 460 * check for a SecurityManager and {@code RuntimePermission("manageProcess")}. 461 * 462 * @implSpec 463 * This implementation throws an instance of 464 * {@link java.lang.UnsupportedOperationException} and performs no other action. 465 * Subclasses should override this method to provide a ProcessHandle for the 466 * process. The methods {@link #pid}, {@link #info}, {@link #children}, 467 * and {@link #descendants}, unless overridden, operate on the ProcessHandle. 468 * 469 * @return Returns a ProcessHandle for the Process 470 * @throws UnsupportedOperationException if the Process implementation 471 * does not support this operation 472 * @throws SecurityException if a security manager has been installed and 473 * it denies RuntimePermission("manageProcess") 474 * @since 9 475 */ 476 public ProcessHandle toHandle() { 477 throw new UnsupportedOperationException(this.getClass() 478 + ".toHandle() not supported"); 479 } 480 481 /** 482 * Returns a snapshot of information about the process. 483 * 484 * <p> A {@link ProcessHandle.Info} instance has accessor methods 485 * that return information about the process if it is available. 486 * 487 * @implSpec 488 * This implementation returns information about the process as: 489 * {@link #toHandle toHandle().info()}. 490 * 491 * @return a snapshot of information about the process, always non-null 492 * @throws UnsupportedOperationException if the Process implementation 493 * does not support this operation 494 * @since 9 495 */ 496 public ProcessHandle.Info info() { 497 return toHandle().info(); 498 } 499 500 /** 501 * Returns a snapshot of the direct children of the process. 502 * The parent of a direct child process is the process. 503 * Typically, a process that is {@linkplain #isAlive not alive} has no children. 504 * <p> 505 * <em>Note that processes are created and terminate asynchronously. 506 * There is no guarantee that a process is {@linkplain #isAlive alive}. 507 * </em> 508 * 509 * @implSpec 510 * This implementation returns the direct children as: 511 * {@link #toHandle toHandle().children()}. 512 * 513 * @return a sequential Stream of ProcessHandles for processes that are 514 * direct children of the process 515 * @throws UnsupportedOperationException if the Process implementation 516 * does not support this operation 517 * @throws SecurityException if a security manager has been installed and 518 * it denies RuntimePermission("manageProcess") 519 * @since 9 520 */ 521 public Stream<ProcessHandle> children() { 522 return toHandle().children(); 523 } 524 525 /** 526 * Returns a snapshot of the descendants of the process. 527 * The descendants of a process are the children of the process 528 * plus the descendants of those children, recursively. 529 * Typically, a process that is {@linkplain #isAlive not alive} has no children. 530 * <p> 531 * <em>Note that processes are created and terminate asynchronously. 532 * There is no guarantee that a process is {@linkplain #isAlive alive}. 533 * </em> 534 * 535 * @implSpec 536 * This implementation returns all children as: 537 * {@link #toHandle toHandle().descendants()}. 538 * 539 * @return a sequential Stream of ProcessHandles for processes that 540 * are descendants of the process 541 * @throws UnsupportedOperationException if the Process implementation 542 * does not support this operation 543 * @throws SecurityException if a security manager has been installed and 544 * it denies RuntimePermission("manageProcess") 545 * @since 9 546 */ 547 public Stream<ProcessHandle> descendants() { 548 return toHandle().descendants(); 549 } 550 551 /** 552 * An input stream for a subprocess pipe that skips by reading bytes 553 * instead of seeking, the underlying pipe does not support seek. 554 */ 555 static class PipeInputStream extends FileInputStream { 556 557 PipeInputStream(FileDescriptor fd) { 558 super(fd); 559 } 560 561 @Override 562 public long skip(long n) throws IOException { 563 long remaining = n; 564 int nr; 565 566 if (n <= 0) { 567 return 0; 568 } 569 570 int size = (int)Math.min(2048, remaining); 571 byte[] skipBuffer = new byte[size]; 572 while (remaining > 0) { 573 nr = read(skipBuffer, 0, (int)Math.min(size, remaining)); 574 if (nr < 0) { 575 break; 576 } 577 remaining -= nr; 578 } 579 580 return n - remaining; 581 } 582 } 583} 584