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.BufferedInputStream; 29 import java.io.BufferedOutputStream; 30 import java.io.ByteArrayInputStream; 31 import java.io.FileDescriptor; 32 import java.io.FileInputStream; 33 import java.io.FileOutputStream; 34 import java.io.IOException; 35 import java.io.InputStream; 36 import java.io.OutputStream; 37 import java.nio.charset.Charset; 38 import java.nio.file.Files; 39 import java.nio.file.LinkOption; 40 import java.nio.file.Path; 41 import java.nio.file.Paths; 42 import java.util.Arrays; 43 import java.util.concurrent.Executors; 44 import java.util.concurrent.Executor; 45 import java.util.concurrent.ThreadFactory; 46 import java.util.concurrent.TimeUnit; 47 import java.security.AccessController; 48 import static java.security.AccessController.doPrivileged; 49 import java.security.PrivilegedAction; 50 import java.security.PrivilegedActionException; 51 import java.security.PrivilegedExceptionAction; 52 53 /** 54 * java.lang.Process subclass in the UNIX environment. 55 * 56 * @author Mario Wolczko and Ross Knippel. 57 * @author Konstantin Kladko (ported to Linux) 58 * @author Martin Buchholz 59 */ 60 final class UNIXProcess extends Process { 61 private static final sun.misc.JavaIOFileDescriptorAccess fdAccess 62 = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess(); 63 64 private final int pid; 65 private int exitcode; 66 private boolean hasExited; 67 68 private /* final */ OutputStream stdin; 69 private /* final */ InputStream stdout; 70 private /* final */ InputStream stderr; 71 72 /* this is for the reaping thread */ 73 private native int waitForProcessExit(int pid); 74 75 /** 76 * Create a process using fork(2) and exec(2). 77 * 78 * @param fds an array of three file descriptors. 79 * Indexes 0, 1, and 2 correspond to standard input, 80 * standard output and standard error, respectively. On 81 * input, a value of -1 means to create a pipe to connect 82 * child and parent processes. On output, a value which 83 * is not -1 is the parent pipe fd corresponding to the 84 * pipe which has been created. An element of this array 85 * is -1 on input if and only if it is <em>not</em> -1 on 86 * output. 87 * @return the pid of the subprocess 88 */ 89 private native int forkAndExec(byte[] prog, 90 byte[] argBlock, int argc, 91 byte[] envBlock, int envc, 92 byte[] dir, 93 int[] fds, 94 boolean redirectErrorStream) 95 throws IOException; 96 97 /** 98 * The thread factory used to create "process reaper" daemon threads. 99 */ 100 private static class ProcessReaperThreadFactory implements ThreadFactory { 101 private final static ThreadGroup group = getRootThreadGroup(); 102 103 private static ThreadGroup getRootThreadGroup() { 104 return doPrivileged(new PrivilegedAction<ThreadGroup> () { 105 public ThreadGroup run() { 106 ThreadGroup root = Thread.currentThread().getThreadGroup(); 107 while (root.getParent() != null) 108 root = root.getParent(); 109 return root; 110 }}); 111 } 112 113 public Thread newThread(Runnable grimReaper) { 114 // Our thread stack requirement is quite modest. 115 Thread t = new Thread(group, grimReaper, "process reaper", 32768); 116 t.setDaemon(true); 117 // A small attempt (probably futile) to avoid priority inversion 118 t.setPriority(Thread.MAX_PRIORITY); 119 return t; 120 } 121 } 122 123 /** 124 * The thread pool of "process reaper" daemon threads. 125 */ 126 private static final Executor processReaperExecutor = 127 doPrivileged(new PrivilegedAction<Executor>() { 128 public Executor run() { 129 return Executors.newCachedThreadPool 130 (new ProcessReaperThreadFactory()); 131 }}); 132 133 UNIXProcess(final byte[] prog, 134 final byte[] argBlock, final int argc, 135 final byte[] envBlock, final int envc, 136 final byte[] dir, 137 final int[] fds, 138 final boolean redirectErrorStream) 139 throws IOException { 140 141 pid = forkAndExec(prog, 142 argBlock, argc, 143 envBlock, envc, 144 dir, 145 fds, 146 redirectErrorStream); 147 148 try { 149 doPrivileged(new PrivilegedExceptionAction<Void>() { 150 public Void run() throws IOException { 151 initStreams(fds); 152 return null; 153 }}); 154 } catch (PrivilegedActionException ex) { 155 throw (IOException) ex.getException(); 156 } 157 } 158 159 static FileDescriptor newFileDescriptor(int fd) { 160 FileDescriptor fileDescriptor = new FileDescriptor(); 161 fdAccess.set(fileDescriptor, fd); 162 return fileDescriptor; 163 } 164 165 void initStreams(int[] fds) throws IOException { 166 stdin = (fds[0] == -1) ? 167 ProcessBuilder.NullOutputStream.INSTANCE : 168 new ProcessPipeOutputStream(fds[0]); 169 170 stdout = (fds[1] == -1) ? 171 ProcessBuilder.NullInputStream.INSTANCE : 172 new ProcessPipeInputStream(fds[1]); 173 174 stderr = (fds[2] == -1) ? 175 ProcessBuilder.NullInputStream.INSTANCE : 176 new ProcessPipeInputStream(fds[2]); 177 178 processReaperExecutor.execute(new Runnable() { 179 public void run() { 180 int exitcode = waitForProcessExit(pid); 181 UNIXProcess.this.processExited(exitcode); 182 }}); 183 } 184 185 void processExited(int exitcode) { 186 synchronized (this) { 187 this.exitcode = exitcode; 188 hasExited = true; 189 notifyAll(); 190 } 191 192 if (stdout instanceof ProcessPipeInputStream) 193 ((ProcessPipeInputStream) stdout).processExited(); 194 195 if (stderr instanceof ProcessPipeInputStream) 196 ((ProcessPipeInputStream) stderr).processExited(); 197 198 if (stdin instanceof ProcessPipeOutputStream) 199 ((ProcessPipeOutputStream) stdin).processExited(); 200 } 201 202 public OutputStream getOutputStream() { 203 return stdin; 204 } 205 206 public InputStream getInputStream() { 207 return stdout; 208 } 209 210 public InputStream getErrorStream() { 211 return stderr; 212 } 213 214 public synchronized int waitFor() throws InterruptedException { 215 while (!hasExited) { 216 wait(); 217 } 218 return exitcode; 219 } 220 221 @Override 222 public synchronized boolean waitFor(long timeout, TimeUnit unit) 223 throws InterruptedException 224 { 225 if (hasExited) return true; 226 if (timeout <= 0) return false; 227 228 long timeoutAsNanos = unit.toNanos(timeout); 229 long startTime = System.nanoTime(); 230 long rem = timeoutAsNanos; 231 232 while (!hasExited && (rem > 0)) { 233 wait(Math.max(TimeUnit.NANOSECONDS.toMillis(rem), 1)); 234 rem = timeoutAsNanos - (System.nanoTime() - startTime); 235 } 236 return hasExited; 237 } 238 239 public synchronized int exitValue() { 240 if (!hasExited) { 241 throw new IllegalThreadStateException("process hasn't exited"); 242 } 243 return exitcode; 244 } 245 246 private static native void destroyProcess(int pid, boolean force); 247 private void destroy(boolean force) { 248 // There is a risk that pid will be recycled, causing us to 249 // kill the wrong process! So we only terminate processes 250 // that appear to still be running. Even with this check, 251 // there is an unavoidable race condition here, but the window 252 // is very small, and OSes try hard to not recycle pids too 253 // soon, so this is quite safe. 254 synchronized (this) { 255 if (!hasExited) 256 destroyProcess(pid, force); 257 } 258 try { stdin.close(); } catch (IOException ignored) {} 259 try { stdout.close(); } catch (IOException ignored) {} 260 try { stderr.close(); } catch (IOException ignored) {} 261 } 262 263 public void destroy() { 264 destroy(false); 265 } 266 267 @Override 268 public Process destroyForcibly() { 269 destroy(true); 270 return this; 271 } 272 273 @Override 274 public synchronized boolean isAlive() { 275 return !hasExited; 276 } 277 278 @Override 279 public int getPid() { 280 if (!isAlive()) { 281 return -1; 282 } else { 283 return pid; 284 } 285 } 286 287 @Override 288 public String getProcessName(int pid) { 289 // look at /proc/<pid>/comm 290 if (pid < 0) { 291 throw new IllegalArgumentException( "pid == " + pid ); 292 } 293 Path p = Paths.get( "/proc/" + pid + "/comm" ); 294 if (!Files.exists(p, LinkOption.NOFOLLOW_LINKS )) { 295 return null; 296 } 297 298 try { 299 return Files.readAllLines( p, Charset.defaultCharset() ).get(0); 300 } catch (IOException ioex) { 301 throw new RuntimeException( ioex ); 302 } 303 } 304 305 /* This routine initializes JNI field offsets for the class */ 306 private static native void initIDs(); 307 308 static { 309 initIDs(); 310 } 311 312 /** 313 * A buffered input stream for a subprocess pipe file descriptor 314 * that allows the underlying file descriptor to be reclaimed when 315 * the process exits, via the processExited hook. 316 * 317 * This is tricky because we do not want the user-level InputStream to be 318 * closed until the user invokes close(), and we need to continue to be 319 * able to read any buffered data lingering in the OS pipe buffer. 320 */ 321 static class ProcessPipeInputStream extends BufferedInputStream { 322 ProcessPipeInputStream(int fd) { 323 super(new FileInputStream(newFileDescriptor(fd))); 324 } 325 326 private static byte[] drainInputStream(InputStream in) 327 throws IOException { 328 if (in == null) return null; 329 int n = 0; 330 int j; 331 byte[] a = null; 332 while ((j = in.available()) > 0) { 333 a = (a == null) ? new byte[j] : Arrays.copyOf(a, n + j); 334 n += in.read(a, n, j); 335 } 336 return (a == null || n == a.length) ? a : Arrays.copyOf(a, n); 337 } 338 339 /** Called by the process reaper thread when the process exits. */ 340 synchronized void processExited() { 341 // Most BufferedInputStream methods are synchronized, but close() 342 // is not, and so we have to handle concurrent racing close(). 343 try { 344 InputStream in = this.in; 345 if (in != null) { 346 byte[] stragglers = drainInputStream(in); 347 in.close(); 348 this.in = (stragglers == null) ? 349 ProcessBuilder.NullInputStream.INSTANCE : 350 new ByteArrayInputStream(stragglers); 351 if (buf == null) // asynchronous close()? 352 this.in = null; 353 } 354 } catch (IOException ignored) { 355 // probably an asynchronous close(). 356 } 357 } 358 } 359 360 /** 361 * A buffered output stream for a subprocess pipe file descriptor 362 * that allows the underlying file descriptor to be reclaimed when 363 * the process exits, via the processExited hook. 364 */ 365 static class ProcessPipeOutputStream extends BufferedOutputStream { 366 ProcessPipeOutputStream(int fd) { 367 super(new FileOutputStream(newFileDescriptor(fd))); 368 } 369 370 /** Called by the process reaper thread when the process exits. */ 371 synchronized void processExited() { 372 OutputStream out = this.out; 373 if (out != null) { 374 try { 375 out.close(); 376 } catch (IOException ignored) { 377 // We know of no reason to get an IOException, but if 378 // we do, there's nothing else to do but carry on. 379 } 380 this.out = ProcessBuilder.NullOutputStream.INSTANCE; 381 } 382 } 383 } 384 }