1 /* 2 * Copyright (c) 1995, 2019, 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.lang.ProcessBuilder.Redirect; 30 import java.util.concurrent.CompletableFuture; 31 import java.util.concurrent.ForkJoinPool; 32 import java.util.concurrent.TimeUnit; 33 import 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 */ 92 public 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 remainingNanos = unit.toNanos(timeout); // throw NPE before other conditions 210 if (hasExited()) return true; 211 if (timeout <= 0) return false; 212 213 long deadline = System.nanoTime() + remainingNanos; 214 do { 215 Thread.sleep(Math.min(TimeUnit.NANOSECONDS.toMillis(remainingNanos) + 1, 100)); 216 if (hasExited()) return true; 217 remainingNanos = deadline - System.nanoTime(); 218 } while (remainingNanos > 0); 219 return false; 220 } 221 222 /** 223 * Returns the exit value for the process. 224 * 225 * @return the exit value of the process represented by this 226 * {@code Process} object. By convention, the value 227 * {@code 0} indicates normal termination. 228 * @throws IllegalThreadStateException if the process represented 229 * by this {@code Process} object has not yet terminated 230 */ 231 public abstract int exitValue(); 232 233 /** 234 * Kills the process. 235 * Whether the process represented by this {@code Process} object is 236 * {@linkplain #supportsNormalTermination normally terminated} or not is 237 * implementation dependent. 238 * Forcible process destruction is defined as the immediate termination of a 239 * process, whereas normal termination allows the process to shut down cleanly. 240 * If the process is not alive, no action is taken. 241 * <p> 242 * The {@link java.util.concurrent.CompletableFuture} from {@link #onExit} is 243 * {@linkplain java.util.concurrent.CompletableFuture#complete completed} 244 * when the process has terminated. 245 */ 246 public abstract void destroy(); 247 248 /** 249 * Kills the process forcibly. The process represented by this 250 * {@code Process} object is forcibly terminated. 251 * Forcible process destruction is defined as the immediate termination of a 252 * process, whereas normal termination allows the process to shut down cleanly. 253 * If the process is not alive, no action is taken. 254 * <p> 255 * The {@link java.util.concurrent.CompletableFuture} from {@link #onExit} is 256 * {@linkplain java.util.concurrent.CompletableFuture#complete completed} 257 * when the process has terminated. 258 * <p> 259 * Invoking this method on {@code Process} objects returned by 260 * {@link ProcessBuilder#start} and {@link Runtime#exec} forcibly terminate 261 * the process. 262 * 263 * @implSpec 264 * The default implementation of this method invokes {@link #destroy} 265 * and so may not forcibly terminate the process. 266 * @implNote 267 * Concrete implementations of this class are strongly encouraged to override 268 * this method with a compliant implementation. 269 * @apiNote 270 * The process may not terminate immediately. 271 * i.e. {@code isAlive()} may return true for a brief period 272 * after {@code destroyForcibly()} is called. This method 273 * may be chained to {@code waitFor()} if needed. 274 * 275 * @return the {@code Process} object representing the 276 * process forcibly destroyed 277 * @since 1.8 278 */ 279 public Process destroyForcibly() { 280 destroy(); 281 return this; 282 } 283 284 /** 285 * Returns {@code true} if the implementation of {@link #destroy} is to 286 * normally terminate the process, 287 * Returns {@code false} if the implementation of {@code destroy} 288 * forcibly and immediately terminates the process. 289 * <p> 290 * Invoking this method on {@code Process} objects returned by 291 * {@link ProcessBuilder#start} and {@link Runtime#exec} return 292 * {@code true} or {@code false} depending on the platform implementation. 293 * 294 * @implSpec 295 * This implementation throws an instance of 296 * {@link java.lang.UnsupportedOperationException} and performs no other action. 297 * 298 * @return {@code true} if the implementation of {@link #destroy} is to 299 * normally terminate the process; 300 * otherwise, {@link #destroy} forcibly terminates the process 301 * @throws UnsupportedOperationException if the Process implementation 302 * does not support this operation 303 * @since 9 304 */ 305 public boolean supportsNormalTermination() { 306 throw new UnsupportedOperationException(this.getClass() 307 + ".supportsNormalTermination() not supported" ); 308 } 309 310 /** 311 * Tests whether the process represented by this {@code Process} is 312 * alive. 313 * 314 * @return {@code true} if the process represented by this 315 * {@code Process} object has not yet terminated. 316 * @since 1.8 317 */ 318 public boolean isAlive() { 319 return !hasExited(); 320 } 321 322 /** 323 * This is called from the default implementation of 324 * {@code waitFor(long, TimeUnit)}, which is specified to poll 325 * {@code exitValue()}. 326 */ 327 private boolean hasExited() { 328 try { 329 exitValue(); 330 return true; 331 } catch (IllegalThreadStateException e) { 332 return false; 333 } 334 } 335 336 /** 337 * Returns the native process ID of the process. 338 * The native process ID is an identification number that the operating 339 * system assigns to the process. 340 * 341 * @implSpec 342 * The implementation of this method returns the process id as: 343 * {@link #toHandle toHandle().pid()}. 344 * 345 * @return the native process id of the process 346 * @throws UnsupportedOperationException if the Process implementation 347 * does not support this operation 348 * @since 9 349 */ 350 public long pid() { 351 return toHandle().pid(); 352 } 353 354 /** 355 * Returns a {@code CompletableFuture<Process>} for the termination of the Process. 356 * The {@link java.util.concurrent.CompletableFuture} provides the ability 357 * to trigger dependent functions or actions that may be run synchronously 358 * or asynchronously upon process termination. 359 * When the process has terminated the CompletableFuture is 360 * {@link java.util.concurrent.CompletableFuture#complete completed} regardless 361 * of the exit status of the process. 362 * <p> 363 * Calling {@code onExit().get()} waits for the process to terminate and returns 364 * the Process. The future can be used to check if the process is 365 * {@linkplain java.util.concurrent.CompletableFuture#isDone done} or to 366 * {@linkplain java.util.concurrent.CompletableFuture#get() wait} for it to terminate. 367 * {@linkplain java.util.concurrent.CompletableFuture#cancel(boolean) Cancelling} 368 * the CompletableFuture does not affect the Process. 369 * <p> 370 * Processes returned from {@link ProcessBuilder#start} override the 371 * default implementation to provide an efficient mechanism to wait 372 * for process exit. 373 * 374 * @apiNote 375 * Using {@link #onExit() onExit} is an alternative to 376 * {@link #waitFor() waitFor} that enables both additional concurrency 377 * and convenient access to the result of the Process. 378 * Lambda expressions can be used to evaluate the result of the Process 379 * execution. 380 * If there is other processing to be done before the value is used 381 * then {@linkplain #onExit onExit} is a convenient mechanism to 382 * free the current thread and block only if and when the value is needed. 383 * <br> 384 * For example, launching a process to compare two files and get a boolean if they are identical: 385 * <pre> {@code Process p = new ProcessBuilder("cmp", "f1", "f2").start(); 386 * Future<Boolean> identical = p.onExit().thenApply(p1 -> p1.exitValue() == 0); 387 * ... 388 * if (identical.get()) { ... } 389 * }</pre> 390 * 391 * @implSpec 392 * This implementation executes {@link #waitFor()} in a separate thread 393 * repeatedly until it returns successfully. If the execution of 394 * {@code waitFor} is interrupted, the thread's interrupt status is preserved. 395 * <p> 396 * When {@link #waitFor()} returns successfully the CompletableFuture is 397 * {@linkplain java.util.concurrent.CompletableFuture#complete completed} regardless 398 * of the exit status of the process. 399 * 400 * This implementation may consume a lot of memory for thread stacks if a 401 * large number of processes are waited for concurrently. 402 * <p> 403 * External implementations should override this method and provide 404 * a more efficient implementation. For example, to delegate to the underlying 405 * process, it can do the following: 406 * <pre>{@code 407 * public CompletableFuture<Process> onExit() { 408 * return delegate.onExit().thenApply(p -> this); 409 * } 410 * }</pre> 411 * @apiNote 412 * The process may be observed to have terminated with {@link #isAlive} 413 * before the ComputableFuture is completed and dependent actions are invoked. 414 * 415 * @return a new {@code CompletableFuture<Process>} for the Process 416 * 417 * @since 9 418 */ 419 public CompletableFuture<Process> onExit() { 420 return CompletableFuture.supplyAsync(this::waitForInternal); 421 } 422 423 /** 424 * Wait for the process to exit by calling {@code waitFor}. 425 * If the thread is interrupted, remember the interrupted state to 426 * be restored before returning. Use ForkJoinPool.ManagedBlocker 427 * so that the number of workers in case ForkJoinPool is used is 428 * compensated when the thread blocks in waitFor(). 429 * 430 * @return the Process 431 */ 432 private Process waitForInternal() { 433 boolean interrupted = false; 434 while (true) { 435 try { 436 ForkJoinPool.managedBlock(new ForkJoinPool.ManagedBlocker() { 437 @Override 438 public boolean block() throws InterruptedException { 439 waitFor(); 440 return true; 441 } 442 443 @Override 444 public boolean isReleasable() { 445 return !isAlive(); 446 } 447 }); 448 break; 449 } catch (InterruptedException x) { 450 interrupted = true; 451 } 452 } 453 if (interrupted) { 454 Thread.currentThread().interrupt(); 455 } 456 return this; 457 } 458 459 /** 460 * Returns a ProcessHandle for the Process. 461 * 462 * {@code Process} objects returned by {@link ProcessBuilder#start} and 463 * {@link Runtime#exec} implement {@code toHandle} as the equivalent of 464 * {@link ProcessHandle#of(long) ProcessHandle.of(pid)} including the 465 * check for a SecurityManager and {@code RuntimePermission("manageProcess")}. 466 * 467 * @implSpec 468 * This implementation throws an instance of 469 * {@link java.lang.UnsupportedOperationException} and performs no other action. 470 * Subclasses should override this method to provide a ProcessHandle for the 471 * process. The methods {@link #pid}, {@link #info}, {@link #children}, 472 * and {@link #descendants}, unless overridden, operate on the ProcessHandle. 473 * 474 * @return Returns a ProcessHandle for the Process 475 * @throws UnsupportedOperationException if the Process implementation 476 * does not support this operation 477 * @throws SecurityException if a security manager has been installed and 478 * it denies RuntimePermission("manageProcess") 479 * @since 9 480 */ 481 public ProcessHandle toHandle() { 482 throw new UnsupportedOperationException(this.getClass() 483 + ".toHandle() not supported"); 484 } 485 486 /** 487 * Returns a snapshot of information about the process. 488 * 489 * <p> A {@link ProcessHandle.Info} instance has accessor methods 490 * that return information about the process if it is available. 491 * 492 * @implSpec 493 * This implementation returns information about the process as: 494 * {@link #toHandle toHandle().info()}. 495 * 496 * @return a snapshot of information about the process, always non-null 497 * @throws UnsupportedOperationException if the Process implementation 498 * does not support this operation 499 * @since 9 500 */ 501 public ProcessHandle.Info info() { 502 return toHandle().info(); 503 } 504 505 /** 506 * Returns a snapshot of the direct children of the process. 507 * The parent of a direct child process is the process. 508 * Typically, a process that is {@linkplain #isAlive not alive} has no children. 509 * <p> 510 * <em>Note that processes are created and terminate asynchronously. 511 * There is no guarantee that a process is {@linkplain #isAlive alive}. 512 * </em> 513 * 514 * @implSpec 515 * This implementation returns the direct children as: 516 * {@link #toHandle toHandle().children()}. 517 * 518 * @return a sequential Stream of ProcessHandles for processes that are 519 * direct children of the process 520 * @throws UnsupportedOperationException if the Process implementation 521 * does not support this operation 522 * @throws SecurityException if a security manager has been installed and 523 * it denies RuntimePermission("manageProcess") 524 * @since 9 525 */ 526 public Stream<ProcessHandle> children() { 527 return toHandle().children(); 528 } 529 530 /** 531 * Returns a snapshot of the descendants of the process. 532 * The descendants of a process are the children of the process 533 * plus the descendants of those children, recursively. 534 * Typically, a process that is {@linkplain #isAlive not alive} has no children. 535 * <p> 536 * <em>Note that processes are created and terminate asynchronously. 537 * There is no guarantee that a process is {@linkplain #isAlive alive}. 538 * </em> 539 * 540 * @implSpec 541 * This implementation returns all children as: 542 * {@link #toHandle toHandle().descendants()}. 543 * 544 * @return a sequential Stream of ProcessHandles for processes that 545 * are descendants of the process 546 * @throws UnsupportedOperationException if the Process implementation 547 * does not support this operation 548 * @throws SecurityException if a security manager has been installed and 549 * it denies RuntimePermission("manageProcess") 550 * @since 9 551 */ 552 public Stream<ProcessHandle> descendants() { 553 return toHandle().descendants(); 554 } 555 556 /** 557 * An input stream for a subprocess pipe that skips by reading bytes 558 * instead of seeking, the underlying pipe does not support seek. 559 */ 560 static class PipeInputStream extends FileInputStream { 561 562 PipeInputStream(FileDescriptor fd) { 563 super(fd); 564 } 565 566 @Override 567 public long skip(long n) throws IOException { 568 long remaining = n; 569 int nr; 570 571 if (n <= 0) { 572 return 0; 573 } 574 575 int size = (int)Math.min(2048, remaining); 576 byte[] skipBuffer = new byte[size]; 577 while (remaining > 0) { 578 nr = read(skipBuffer, 0, (int)Math.min(size, remaining)); 579 if (nr < 0) { 580 break; 581 } 582 remaining -= nr; 583 } 584 585 return n - remaining; 586 } 587 } 588 }