jdk/src/solaris/classes/java/lang/UNIXProcess.java.bsd
changeset 24407 86ebcdad9698
parent 24406 076ae2d12410
parent 24390 cfe99e4d318b
child 24408 97932f6ad950
equal deleted inserted replaced
24406:076ae2d12410 24407:86ebcdad9698
     1 /*
       
     2  * Copyright (c) 1995, 2013, 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 Bsd)
       
    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     private static enum LaunchMechanism {
       
    68         FORK(1),
       
    69         POSIX_SPAWN(2);
       
    70 
       
    71         private int value;
       
    72         LaunchMechanism(int x) {value = x;}
       
    73     };
       
    74 
       
    75     /* On BSD, the default is to spawn */
       
    76     private static final LaunchMechanism launchMechanism;
       
    77     private static byte[] helperpath;
       
    78 
       
    79     private static byte[] toCString(String s) {
       
    80         if (s == null)
       
    81             return null;
       
    82         byte[] bytes = s.getBytes();
       
    83         byte[] result = new byte[bytes.length + 1];
       
    84         System.arraycopy(bytes, 0,
       
    85                          result, 0,
       
    86                          bytes.length);
       
    87         result[result.length-1] = (byte)0;
       
    88         return result;
       
    89     }
       
    90 
       
    91     static {
       
    92         launchMechanism = AccessController.doPrivileged(
       
    93                 new PrivilegedAction<LaunchMechanism>()
       
    94         {
       
    95             public LaunchMechanism run() {
       
    96                 String javahome = System.getProperty("java.home");
       
    97 
       
    98                 helperpath = toCString(javahome + "/lib/jspawnhelper");
       
    99                 String s = System.getProperty(
       
   100                     "jdk.lang.Process.launchMechanism", "posix_spawn");
       
   101 
       
   102                 try {
       
   103                     return LaunchMechanism.valueOf(s.toUpperCase());
       
   104                 } catch (IllegalArgumentException e) {
       
   105                     throw new Error(s + " is not a supported " +
       
   106                         "process launch mechanism on this platform.");
       
   107                 }
       
   108             }
       
   109         });
       
   110     }
       
   111 
       
   112     /* this is for the reaping thread */
       
   113     private native int waitForProcessExit(int pid);
       
   114 
       
   115     /**
       
   116      * Create a process. Depending on the mode flag, this is done by
       
   117      * one of the following mechanisms.
       
   118      * - fork(2) and exec(2)
       
   119      * - posix_spawn(2)
       
   120      *
       
   121      * @param fds an array of three file descriptors.
       
   122      *        Indexes 0, 1, and 2 correspond to standard input,
       
   123      *        standard output and standard error, respectively.  On
       
   124      *        input, a value of -1 means to create a pipe to connect
       
   125      *        child and parent processes.  On output, a value which
       
   126      *        is not -1 is the parent pipe fd corresponding to the
       
   127      *        pipe which has been created.  An element of this array
       
   128      *        is -1 on input if and only if it is <em>not</em> -1 on
       
   129      *        output.
       
   130      * @return the pid of the subprocess
       
   131      */
       
   132     private native int forkAndExec(int mode, byte[] helperpath,
       
   133                                    byte[] prog,
       
   134                                    byte[] argBlock, int argc,
       
   135                                    byte[] envBlock, int envc,
       
   136                                    byte[] dir,
       
   137                                    int[] fds,
       
   138                                    boolean redirectErrorStream)
       
   139         throws IOException;
       
   140 
       
   141     /**
       
   142      * The thread factory used to create "process reaper" daemon threads.
       
   143      */
       
   144     private static class ProcessReaperThreadFactory implements ThreadFactory {
       
   145         private final static ThreadGroup group = getRootThreadGroup();
       
   146 
       
   147         private static ThreadGroup getRootThreadGroup() {
       
   148             return doPrivileged(new PrivilegedAction<ThreadGroup> () {
       
   149                 public ThreadGroup run() {
       
   150                     ThreadGroup root = Thread.currentThread().getThreadGroup();
       
   151                     while (root.getParent() != null)
       
   152                         root = root.getParent();
       
   153                     return root;
       
   154                 }});
       
   155         }
       
   156 
       
   157         public Thread newThread(Runnable grimReaper) {
       
   158             // Our thread stack requirement is quite modest.
       
   159             Thread t = new Thread(group, grimReaper, "process reaper", 32768);
       
   160             t.setDaemon(true);
       
   161             // A small attempt (probably futile) to avoid priority inversion
       
   162             t.setPriority(Thread.MAX_PRIORITY);
       
   163             return t;
       
   164         }
       
   165     }
       
   166 
       
   167     /**
       
   168      * The thread pool of "process reaper" daemon threads.
       
   169      */
       
   170     private static final Executor processReaperExecutor =
       
   171         doPrivileged(new PrivilegedAction<Executor>() {
       
   172             public Executor run() {
       
   173                 return Executors.newCachedThreadPool
       
   174                     (new ProcessReaperThreadFactory());
       
   175             }});
       
   176 
       
   177     UNIXProcess(final byte[] prog,
       
   178                 final byte[] argBlock, final int argc,
       
   179                 final byte[] envBlock, final int envc,
       
   180                 final byte[] dir,
       
   181                 final int[] fds,
       
   182                 final boolean redirectErrorStream)
       
   183             throws IOException {
       
   184 
       
   185         pid = forkAndExec(launchMechanism.value,
       
   186                           helperpath,
       
   187                           prog,
       
   188                           argBlock, argc,
       
   189                           envBlock, envc,
       
   190                           dir,
       
   191                           fds,
       
   192                           redirectErrorStream);
       
   193 
       
   194         try {
       
   195             doPrivileged(new PrivilegedExceptionAction<Void>() {
       
   196                 public Void run() throws IOException {
       
   197                     initStreams(fds);
       
   198                     return null;
       
   199                 }});
       
   200         } catch (PrivilegedActionException ex) {
       
   201             throw (IOException) ex.getException();
       
   202         }
       
   203     }
       
   204 
       
   205     static FileDescriptor newFileDescriptor(int fd) {
       
   206         FileDescriptor fileDescriptor = new FileDescriptor();
       
   207         fdAccess.set(fileDescriptor, fd);
       
   208         return fileDescriptor;
       
   209     }
       
   210 
       
   211     void initStreams(int[] fds) throws IOException {
       
   212         stdin = (fds[0] == -1) ?
       
   213             ProcessBuilder.NullOutputStream.INSTANCE :
       
   214             new ProcessPipeOutputStream(fds[0]);
       
   215 
       
   216         stdout = (fds[1] == -1) ?
       
   217             ProcessBuilder.NullInputStream.INSTANCE :
       
   218             new ProcessPipeInputStream(fds[1]);
       
   219 
       
   220         stderr = (fds[2] == -1) ?
       
   221             ProcessBuilder.NullInputStream.INSTANCE :
       
   222             new ProcessPipeInputStream(fds[2]);
       
   223 
       
   224         processReaperExecutor.execute(new Runnable() {
       
   225             public void run() {
       
   226                 int exitcode = waitForProcessExit(pid);
       
   227                 UNIXProcess.this.processExited(exitcode);
       
   228             }});
       
   229     }
       
   230 
       
   231     void processExited(int exitcode) {
       
   232         synchronized (this) {
       
   233             this.exitcode = exitcode;
       
   234             hasExited = true;
       
   235             notifyAll();
       
   236         }
       
   237 
       
   238         if (stdout instanceof ProcessPipeInputStream)
       
   239             ((ProcessPipeInputStream) stdout).processExited();
       
   240 
       
   241         if (stderr instanceof ProcessPipeInputStream)
       
   242             ((ProcessPipeInputStream) stderr).processExited();
       
   243 
       
   244         if (stdin instanceof ProcessPipeOutputStream)
       
   245             ((ProcessPipeOutputStream) stdin).processExited();
       
   246     }
       
   247 
       
   248     public OutputStream getOutputStream() {
       
   249         return stdin;
       
   250     }
       
   251 
       
   252     public InputStream getInputStream() {
       
   253         return stdout;
       
   254     }
       
   255 
       
   256     public InputStream getErrorStream() {
       
   257         return stderr;
       
   258     }
       
   259 
       
   260     public synchronized int waitFor() throws InterruptedException {
       
   261         while (!hasExited) {
       
   262             wait();
       
   263         }
       
   264         return exitcode;
       
   265     }
       
   266 
       
   267     @Override
       
   268     public synchronized boolean waitFor(long timeout, TimeUnit unit)
       
   269         throws InterruptedException
       
   270     {
       
   271         if (hasExited) return true;
       
   272         if (timeout <= 0) return false;
       
   273 
       
   274         long timeoutAsNanos = unit.toNanos(timeout);
       
   275         long startTime = System.nanoTime();
       
   276         long rem = timeoutAsNanos;
       
   277 
       
   278         while (!hasExited && (rem > 0)) {
       
   279             wait(Math.max(TimeUnit.NANOSECONDS.toMillis(rem), 1));
       
   280             rem = timeoutAsNanos - (System.nanoTime() - startTime);
       
   281         }
       
   282         return hasExited;
       
   283     }
       
   284 
       
   285     public synchronized int exitValue() {
       
   286         if (!hasExited) {
       
   287             throw new IllegalThreadStateException("process hasn't exited");
       
   288         }
       
   289         return exitcode;
       
   290     }
       
   291 
       
   292     private static native void destroyProcess(int pid, boolean force);
       
   293     private void destroy(boolean force) {
       
   294         // There is a risk that pid will be recycled, causing us to
       
   295         // kill the wrong process!  So we only terminate processes
       
   296         // that appear to still be running.  Even with this check,
       
   297         // there is an unavoidable race condition here, but the window
       
   298         // is very small, and OSes try hard to not recycle pids too
       
   299         // soon, so this is quite safe.
       
   300         synchronized (this) {
       
   301             if (!hasExited)
       
   302                 destroyProcess(pid, force);
       
   303         }
       
   304         try { stdin.close();  } catch (IOException ignored) {}
       
   305         try { stdout.close(); } catch (IOException ignored) {}
       
   306         try { stderr.close(); } catch (IOException ignored) {}
       
   307     }
       
   308 
       
   309     public void destroy() {
       
   310         destroy(false);
       
   311     }
       
   312 
       
   313     @Override
       
   314     public Process destroyForcibly() {
       
   315         destroy(true);
       
   316         return this;
       
   317     }
       
   318 
       
   319     @Override
       
   320     public synchronized boolean isAlive() {
       
   321         return !hasExited;
       
   322     }
       
   323 
       
   324     private static native void init();
       
   325 
       
   326     static {
       
   327         init();
       
   328     }
       
   329 
       
   330     /**
       
   331      * A buffered input stream for a subprocess pipe file descriptor
       
   332      * that allows the underlying file descriptor to be reclaimed when
       
   333      * the process exits, via the processExited hook.
       
   334      *
       
   335      * This is tricky because we do not want the user-level InputStream to be
       
   336      * closed until the user invokes close(), and we need to continue to be
       
   337      * able to read any buffered data lingering in the OS pipe buffer.
       
   338      */
       
   339     static class ProcessPipeInputStream extends BufferedInputStream {
       
   340         private final Object closeLock = new Object();
       
   341 
       
   342         ProcessPipeInputStream(int fd) {
       
   343             super(new FileInputStream(newFileDescriptor(fd)));
       
   344         }
       
   345         private static byte[] drainInputStream(InputStream in)
       
   346                 throws IOException {
       
   347             int n = 0;
       
   348             int j;
       
   349             byte[] a = null;
       
   350             while ((j = in.available()) > 0) {
       
   351                 a = (a == null) ? new byte[j] : Arrays.copyOf(a, n + j);
       
   352                 n += in.read(a, n, j);
       
   353             }
       
   354             return (a == null || n == a.length) ? a : Arrays.copyOf(a, n);
       
   355         }
       
   356 
       
   357         /** Called by the process reaper thread when the process exits. */
       
   358         synchronized void processExited() {
       
   359             synchronized (closeLock) {
       
   360                 try {
       
   361                     InputStream in = this.in;
       
   362                     // this stream is closed if and only if: in == null
       
   363                     if (in != null) {
       
   364                         byte[] stragglers = drainInputStream(in);
       
   365                         in.close();
       
   366                         this.in = (stragglers == null) ?
       
   367                             ProcessBuilder.NullInputStream.INSTANCE :
       
   368                             new ByteArrayInputStream(stragglers);
       
   369                     }
       
   370                 } catch (IOException ignored) {}
       
   371             }
       
   372         }
       
   373 
       
   374         @Override
       
   375         public void close() throws IOException {
       
   376             // BufferedInputStream#close() is not synchronized unlike most other methods.
       
   377             // Synchronizing helps avoid race with processExited().
       
   378             synchronized (closeLock) {
       
   379                 super.close();
       
   380             }
       
   381         }
       
   382     }
       
   383 
       
   384     /**
       
   385      * A buffered output stream for a subprocess pipe file descriptor
       
   386      * that allows the underlying file descriptor to be reclaimed when
       
   387      * the process exits, via the processExited hook.
       
   388      */
       
   389     static class ProcessPipeOutputStream extends BufferedOutputStream {
       
   390         ProcessPipeOutputStream(int fd) {
       
   391             super(new FileOutputStream(newFileDescriptor(fd)));
       
   392         }
       
   393 
       
   394         /** Called by the process reaper thread when the process exits. */
       
   395         synchronized void processExited() {
       
   396             OutputStream out = this.out;
       
   397             if (out != null) {
       
   398                 try {
       
   399                     out.close();
       
   400                 } catch (IOException ignored) {
       
   401                     // We know of no reason to get an IOException, but if
       
   402                     // we do, there's nothing else to do but carry on.
       
   403                 }
       
   404                 this.out = ProcessBuilder.NullOutputStream.INSTANCE;
       
   405             }
       
   406         }
       
   407     }
       
   408 }