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.util.Arrays;
  38 import java.util.concurrent.Executors;
  39 import java.util.concurrent.Executor;
  40 import java.util.concurrent.ThreadFactory;
  41 import java.util.concurrent.TimeUnit;
  42 import java.security.AccessController;
  43 import static java.security.AccessController.doPrivileged;
  44 import java.security.PrivilegedAction;
  45 import java.security.PrivilegedActionException;
  46 import java.security.PrivilegedExceptionAction;
  47 
  48 /**
  49  * java.lang.Process subclass in the UNIX environment.
  50  *
  51  * @author Mario Wolczko and Ross Knippel.
  52  * @author Konstantin Kladko (ported to Linux)
  53  * @author Martin Buchholz
  54  */
  55 final class UNIXProcess extends Process {
  56     private static final sun.misc.JavaIOFileDescriptorAccess fdAccess
  57         = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess();
  58 
  59     private final int pid;
  60     private int exitcode;
  61     private boolean hasExited;
  62 
  63     private /* final */ OutputStream stdin;
  64     private /* final */ InputStream  stdout;
  65     private /* final */ InputStream  stderr;
  66 






























  67     /* this is for the reaping thread */
  68     private native int waitForProcessExit(int pid);
  69 
  70     /**
  71      * Create a process using fork(2) and exec(2).




  72      *
  73      * @param fds an array of three file descriptors.
  74      *        Indexes 0, 1, and 2 correspond to standard input,
  75      *        standard output and standard error, respectively.  On
  76      *        input, a value of -1 means to create a pipe to connect
  77      *        child and parent processes.  On output, a value which
  78      *        is not -1 is the parent pipe fd corresponding to the
  79      *        pipe which has been created.  An element of this array
  80      *        is -1 on input if and only if it is <em>not</em> -1 on
  81      *        output.
  82      * @return the pid of the subprocess
  83      */
  84     private native int forkAndExec(byte[] prog,
  85                                    byte[] argBlock, int argc,
  86                                    byte[] envBlock, int envc,
  87                                    byte[] dir,
  88                                    int[] fds,
  89                                    boolean redirectErrorStream)
  90         throws IOException;
  91 
  92     /**
  93      * The thread factory used to create "process reaper" daemon threads.
  94      */
  95     private static class ProcessReaperThreadFactory implements ThreadFactory {
  96         private final static ThreadGroup group = getRootThreadGroup();
  97 
  98         private static ThreadGroup getRootThreadGroup() {
  99             return doPrivileged(new PrivilegedAction<ThreadGroup> () {
 100                 public ThreadGroup run() {
 101                     ThreadGroup root = Thread.currentThread().getThreadGroup();
 102                     while (root.getParent() != null)
 103                         root = root.getParent();
 104                     return root;
 105                 }});
 106         }
 107 
 108         public Thread newThread(Runnable grimReaper) {
 109             // Our thread stack requirement is quite modest.
 110             Thread t = new Thread(group, grimReaper, "process reaper", 32768);
 111             t.setDaemon(true);
 112             // A small attempt (probably futile) to avoid priority inversion
 113             t.setPriority(Thread.MAX_PRIORITY);
 114             return t;
 115         }
 116     }
 117 
 118     /**
 119      * The thread pool of "process reaper" daemon threads.
 120      */
 121     private static final Executor processReaperExecutor =
 122         doPrivileged(new PrivilegedAction<Executor>() {
 123             public Executor run() {
 124                 return Executors.newCachedThreadPool
 125                     (new ProcessReaperThreadFactory());
 126             }});
 127 
 128     UNIXProcess(final byte[] prog,
 129                 final byte[] argBlock, final int argc,
 130                 final byte[] envBlock, final int envc,
 131                 final byte[] dir,
 132                 final int[] fds,
 133                 final boolean redirectErrorStream)
 134             throws IOException {
 135 
 136         pid = forkAndExec(prog,

 137                           argBlock, argc,
 138                           envBlock, envc,
 139                           dir,
 140                           fds,
 141                           redirectErrorStream);
 142 
 143         try {
 144             doPrivileged(new PrivilegedExceptionAction<Void>() {
 145                 public Void run() throws IOException {
 146                     initStreams(fds);
 147                     return null;
 148                 }});
 149         } catch (PrivilegedActionException ex) {
 150             throw (IOException) ex.getException();
 151         }
 152     }
 153 
 154     static FileDescriptor newFileDescriptor(int fd) {
 155         FileDescriptor fileDescriptor = new FileDescriptor();
 156         fdAccess.set(fileDescriptor, fd);
 157         return fileDescriptor;
 158     }
 159 
 160     void initStreams(int[] fds) throws IOException {
 161         stdin = (fds[0] == -1) ?
 162             ProcessBuilder.NullOutputStream.INSTANCE :
 163             new ProcessPipeOutputStream(fds[0]);
 164 
 165         stdout = (fds[1] == -1) ?
 166             ProcessBuilder.NullInputStream.INSTANCE :
 167             new ProcessPipeInputStream(fds[1]);
 168 
 169         stderr = (fds[2] == -1) ?
 170             ProcessBuilder.NullInputStream.INSTANCE :
 171             new ProcessPipeInputStream(fds[2]);
 172 
 173         processReaperExecutor.execute(new Runnable() {
 174             public void run() {
 175                 int exitcode = waitForProcessExit(pid);
 176                 UNIXProcess.this.processExited(exitcode);
 177             }});
 178     }
 179 
 180     void processExited(int exitcode) {
 181         synchronized (this) {
 182             this.exitcode = exitcode;
 183             hasExited = true;
 184             notifyAll();
 185         }
 186 
 187         if (stdout instanceof ProcessPipeInputStream)
 188             ((ProcessPipeInputStream) stdout).processExited();
 189 
 190         if (stderr instanceof ProcessPipeInputStream)
 191             ((ProcessPipeInputStream) stderr).processExited();
 192 
 193         if (stdin instanceof ProcessPipeOutputStream)
 194             ((ProcessPipeOutputStream) stdin).processExited();
 195     }
 196 
 197     public OutputStream getOutputStream() {
 198         return stdin;
 199     }
 200 
 201     public InputStream getInputStream() {
 202         return stdout;
 203     }
 204 
 205     public InputStream getErrorStream() {
 206         return stderr;
 207     }
 208 
 209     public synchronized int waitFor() throws InterruptedException {
 210         while (!hasExited) {
 211             wait();
 212         }
 213         return exitcode;
 214     }
 215 
 216     @Override
 217     public synchronized boolean waitFor(long timeout, TimeUnit unit)
 218         throws InterruptedException
 219     {
 220         if (hasExited) return true;
 221         if (timeout <= 0) return false;
 222 
 223         long timeoutAsNanos = unit.toNanos(timeout);
 224         long startTime = System.nanoTime();
 225         long rem = timeoutAsNanos;
 226 
 227         while (!hasExited && (rem > 0)) {
 228             wait(Math.max(TimeUnit.NANOSECONDS.toMillis(rem), 1));
 229             rem = timeoutAsNanos - (System.nanoTime() - startTime);
 230         }
 231         return hasExited;
 232     }
 233 
 234     public synchronized int exitValue() {
 235         if (!hasExited) {
 236             throw new IllegalThreadStateException("process hasn't exited");
 237         }
 238         return exitcode;
 239     }
 240 
 241     private static native void destroyProcess(int pid, boolean force);
 242     private void destroy(boolean force) {
 243         // There is a risk that pid will be recycled, causing us to
 244         // kill the wrong process!  So we only terminate processes
 245         // that appear to still be running.  Even with this check,
 246         // there is an unavoidable race condition here, but the window
 247         // is very small, and OSes try hard to not recycle pids too
 248         // soon, so this is quite safe.
 249         synchronized (this) {
 250             if (!hasExited)
 251                 destroyProcess(pid, force);
 252         }
 253         try { stdin.close();  } catch (IOException ignored) {}
 254         try { stdout.close(); } catch (IOException ignored) {}
 255         try { stderr.close(); } catch (IOException ignored) {}
 256     }
 257 
 258     public void destroy() {
 259         destroy(false);
 260     }
 261 
 262     @Override
 263     public Process destroyForcibly() {
 264         destroy(true);
 265         return this;
 266     }
 267 
 268     @Override
 269     public synchronized boolean isAlive() {
 270         return !hasExited;
 271     }
 272 
 273     /* This routine initializes JNI field offsets for the class */
 274     private static native void initIDs();
 275 
 276     static {
 277         initIDs();
 278     }
 279 
 280     /**
 281      * A buffered input stream for a subprocess pipe file descriptor
 282      * that allows the underlying file descriptor to be reclaimed when
 283      * the process exits, via the processExited hook.
 284      *
 285      * This is tricky because we do not want the user-level InputStream to be
 286      * closed until the user invokes close(), and we need to continue to be
 287      * able to read any buffered data lingering in the OS pipe buffer.
 288      */
 289     static class ProcessPipeInputStream extends BufferedInputStream {
 290         ProcessPipeInputStream(int fd) {
 291             super(new FileInputStream(newFileDescriptor(fd)));
 292         }
 293 
 294         private static byte[] drainInputStream(InputStream in)
 295                 throws IOException {
 296             if (in == null) return null;
 297             int n = 0;
 298             int j;
 299             byte[] a = null;
 300             while ((j = in.available()) > 0) {
 301                 a = (a == null) ? new byte[j] : Arrays.copyOf(a, n + j);
 302                 n += in.read(a, n, j);
 303             }
 304             return (a == null || n == a.length) ? a : Arrays.copyOf(a, n);
 305         }
 306 
 307         /** Called by the process reaper thread when the process exits. */
 308         synchronized void processExited() {
 309             // Most BufferedInputStream methods are synchronized, but close()
 310             // is not, and so we have to handle concurrent racing close().
 311             try {
 312                 InputStream in = this.in;
 313                 if (in != null) {
 314                     byte[] stragglers = drainInputStream(in);
 315                     in.close();
 316                     this.in = (stragglers == null) ?
 317                         ProcessBuilder.NullInputStream.INSTANCE :
 318                         new ByteArrayInputStream(stragglers);
 319                     if (buf == null) // asynchronous close()?
 320                         this.in = null;
 321                 }
 322             } catch (IOException ignored) {
 323                 // probably an asynchronous close().
 324             }
 325         }
 326     }
 327 
 328     /**
 329      * A buffered output stream for a subprocess pipe file descriptor
 330      * that allows the underlying file descriptor to be reclaimed when
 331      * the process exits, via the processExited hook.
 332      */
 333     static class ProcessPipeOutputStream extends BufferedOutputStream {
 334         ProcessPipeOutputStream(int fd) {
 335             super(new FileOutputStream(newFileDescriptor(fd)));
 336         }
 337 
 338         /** Called by the process reaper thread when the process exits. */
 339         synchronized void processExited() {
 340             OutputStream out = this.out;
 341             if (out != null) {
 342                 try {
 343                     out.close();
 344                 } catch (IOException ignored) {
 345                     // We know of no reason to get an IOException, but if
 346                     // we do, there's nothing else to do but carry on.
 347                 }
 348                 this.out = ProcessBuilder.NullOutputStream.INSTANCE;
 349             }
 350         }
 351     }
 352 }
--- EOF ---