UNIXProcess.java.solaris 11.1 KB
Newer Older
1
/*
2
 * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28
 */

package java.lang;

import java.io.*;
29
import java.util.concurrent.TimeUnit;
D
duke 已提交
30 31 32 33 34 35 36

/* java.lang.Process subclass in the UNIX environment.
 *
 * @author Mario Wolczko and Ross Knippel.
 */

final class UNIXProcess extends Process {
37 38 39 40
    private static final sun.misc.JavaIOFileDescriptorAccess fdAccess
        = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess();

    private final int pid;
D
duke 已提交
41 42 43 44
    private int exitcode;
    private boolean hasExited;

    private OutputStream stdin_stream;
45
    private InputStream stdout_stream;
D
duke 已提交
46
    private DeferredCloseInputStream stdout_inner_stream;
47
    private InputStream stderr_stream;
D
duke 已提交
48 49 50 51

    /* this is for the reaping thread */
    private native int waitForProcessExit(int pid);

52 53 54 55 56 57 58 59 60 61 62 63 64
    /**
     * Create a process using fork(2) and exec(2).
     *
     * @param std_fds array of file descriptors.  Indexes 0, 1, and
     *        2 correspond to standard input, standard output and
     *        standard error, respectively.  On input, a value of -1
     *        means to create a pipe to connect child and parent
     *        processes.  On output, a value which is not -1 is the
     *        parent pipe fd corresponding to the pipe which has
     *        been created.  An element of this array is -1 on input
     *        if and only if it is <em>not</em> -1 on output.
     * @return the pid of the subprocess
     */
D
duke 已提交
65
    private native int forkAndExec(byte[] prog,
66 67 68 69 70 71
                                   byte[] argBlock, int argc,
                                   byte[] envBlock, int envc,
                                   byte[] dir,
                                   int[] std_fds,
                                   boolean redirectErrorStream)
        throws IOException;
D
duke 已提交
72 73

    UNIXProcess(final byte[] prog,
74 75 76 77 78
                final byte[] argBlock, int argc,
                final byte[] envBlock, int envc,
                final byte[] dir,
                final int[] std_fds,
                final boolean redirectErrorStream)
D
duke 已提交
79
    throws IOException {
80 81 82 83 84 85 86 87 88 89
        pid = forkAndExec(prog,
                          argBlock, argc,
                          envBlock, envc,
                          dir,
                          std_fds,
                          redirectErrorStream);

        java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<Void>() { public Void run() {
            if (std_fds[0] == -1)
90
                stdin_stream = ProcessBuilder.NullOutputStream.INSTANCE;
91 92 93 94 95 96 97 98
            else {
                FileDescriptor stdin_fd = new FileDescriptor();
                fdAccess.set(stdin_fd, std_fds[0]);
                stdin_stream = new BufferedOutputStream(
                    new FileOutputStream(stdin_fd));
            }

            if (std_fds[1] == -1)
99
                stdout_stream = ProcessBuilder.NullInputStream.INSTANCE;
100 101 102 103 104 105 106 107
            else {
                FileDescriptor stdout_fd = new FileDescriptor();
                fdAccess.set(stdout_fd, std_fds[1]);
                stdout_inner_stream = new DeferredCloseInputStream(stdout_fd);
                stdout_stream = new BufferedInputStream(stdout_inner_stream);
            }

            if (std_fds[2] == -1)
108
                stderr_stream = ProcessBuilder.NullInputStream.INSTANCE;
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
            else {
                FileDescriptor stderr_fd = new FileDescriptor();
                fdAccess.set(stderr_fd, std_fds[2]);
                stderr_stream = new DeferredCloseInputStream(stderr_fd);
            }

            return null; }});

        /*
         * For each subprocess forked a corresponding reaper thread
         * is started.  That thread is the only thread which waits
         * for the subprocess to terminate and it doesn't hold any
         * locks while doing so.  This design allows waitFor() and
         * exitStatus() to be safely executed in parallel (and they
         * need no native code).
         */

        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<Void>() { public Void run() {
                Thread t = new Thread("process reaper") {
                    public void run() {
                        int res = waitForProcessExit(pid);
                        synchronized (UNIXProcess.this) {
                            hasExited = true;
                            exitcode = res;
                            UNIXProcess.this.notifyAll();
                        }
                    }
                };
                t.setDaemon(true);
                t.start();
                return null; }});
D
duke 已提交
141 142 143
    }

    public OutputStream getOutputStream() {
144
        return stdin_stream;
D
duke 已提交
145 146 147
    }

    public InputStream getInputStream() {
148
        return stdout_stream;
D
duke 已提交
149 150 151
    }

    public InputStream getErrorStream() {
152
        return stderr_stream;
D
duke 已提交
153 154 155 156
    }

    public synchronized int waitFor() throws InterruptedException {
        while (!hasExited) {
157 158 159
            wait();
        }
        return exitcode;
D
duke 已提交
160 161
    }

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    @Override
    public synchronized boolean waitFor(long timeout, TimeUnit unit)
        throws InterruptedException
    {
        if (hasExited) return true;
        if (timeout <= 0) return false;

        long timeoutAsNanos = unit.toNanos(timeout);
        long startTime = System.nanoTime();
        long rem = timeoutAsNanos;

        while (!hasExited && (rem > 0)) {
            wait(Math.max(TimeUnit.NANOSECONDS.toMillis(rem), 1));
            rem = timeoutAsNanos - (System.nanoTime() - startTime);
        }
        return hasExited;
    }

D
duke 已提交
180
    public synchronized int exitValue() {
181 182 183 184
        if (!hasExited) {
            throw new IllegalThreadStateException("process hasn't exited");
        }
        return exitcode;
D
duke 已提交
185 186
    }

187 188
    private static native void destroyProcess(int pid, boolean force);
    private synchronized void destroy(boolean force) {
189 190 191 192 193 194 195
        // There is a risk that pid will be recycled, causing us to
        // kill the wrong process!  So we only terminate processes
        // that appear to still be running.  Even with this check,
        // there is an unavoidable race condition here, but the window
        // is very small, and OSes try hard to not recycle pids too
        // soon, so this is quite safe.
        if (!hasExited)
196
            destroyProcess(pid, force);
197
        try {
D
duke 已提交
198
            stdin_stream.close();
199 200 201 202 203
            if (stdout_inner_stream != null)
                stdout_inner_stream.closeDeferred(stdout_stream);
            if (stderr_stream instanceof DeferredCloseInputStream)
                ((DeferredCloseInputStream) stderr_stream)
                    .closeDeferred(stderr_stream);
D
duke 已提交
204 205 206 207 208
        } catch (IOException e) {
            // ignore
        }
    }

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    public void destroy() {
        destroy(false);
    }

    @Override
    public Process destroyForcibly() {
        destroy(true);
        return this;
    }

    @Override
    public synchronized boolean isAlive() {
        return !hasExited;
    }

D
duke 已提交
224 225 226 227 228 229 230 231 232 233 234
    // A FileInputStream that supports the deferment of the actual close
    // operation until the last pending I/O operation on the stream has
    // finished.  This is required on Solaris because we must close the stdin
    // and stdout streams in the destroy method in order to reclaim the
    // underlying file descriptors.  Doing so, however, causes any thread
    // currently blocked in a read on one of those streams to receive an
    // IOException("Bad file number"), which is incompatible with historical
    // behavior.  By deferring the close we allow any pending reads to see -1
    // (EOF) as they did before.
    //
    private static class DeferredCloseInputStream
235
        extends FileInputStream
D
duke 已提交
236 237
    {

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        private DeferredCloseInputStream(FileDescriptor fd) {
            super(fd);
        }

        private Object lock = new Object();     // For the following fields
        private boolean closePending = false;
        private int useCount = 0;
        private InputStream streamToClose;

        private void raise() {
            synchronized (lock) {
                useCount++;
            }
        }

        private void lower() throws IOException {
            synchronized (lock) {
                useCount--;
                if (useCount == 0 && closePending) {
                    streamToClose.close();
                }
            }
        }

        // stc is the actual stream to be closed; it might be this object, or
        // it might be an upstream object for which this object is downstream.
        //
        private void closeDeferred(InputStream stc) throws IOException {
            synchronized (lock) {
                if (useCount == 0) {
                    stc.close();
                } else {
                    closePending = true;
                    streamToClose = stc;
                }
            }
        }

        public void close() throws IOException {
            synchronized (lock) {
                useCount = 0;
                closePending = false;
            }
            super.close();
        }

        public int read() throws IOException {
            raise();
            try {
                return super.read();
            } finally {
                lower();
            }
        }

        public int read(byte[] b) throws IOException {
            raise();
            try {
                return super.read(b);
            } finally {
                lower();
            }
        }

        public int read(byte[] b, int off, int len) throws IOException {
            raise();
            try {
                return super.read(b, off, len);
            } finally {
                lower();
            }
        }

        public long skip(long n) throws IOException {
            raise();
            try {
                return super.skip(n);
            } finally {
                lower();
            }
        }

        public int available() throws IOException {
            raise();
            try {
                return super.available();
            } finally {
                lower();
            }
        }
D
duke 已提交
328 329 330

    }

331
    private static native void init();
D
duke 已提交
332 333

    static {
334
        init();
D
duke 已提交
335 336
    }
}