UNIXProcess.java.linux 14.0 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
 */

package java.lang;

28 29 30 31 32 33 34 35 36 37 38 39 40
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
41
import java.util.concurrent.TimeUnit;
42
import java.security.AccessController;
43
import static java.security.AccessController.doPrivileged;
44 45 46
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
D
duke 已提交
47

48 49
/**
 * java.lang.Process subclass in the UNIX environment.
D
duke 已提交
50 51 52
 *
 * @author Mario Wolczko and Ross Knippel.
 * @author Konstantin Kladko (ported to Linux)
53
 * @author Martin Buchholz
D
duke 已提交
54 55
 */
final class UNIXProcess extends Process {
56 57 58
    private static final sun.misc.JavaIOFileDescriptorAccess fdAccess
        = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess();

59
    private final int pid;
D
duke 已提交
60 61 62
    private int exitcode;
    private boolean hasExited;

63 64 65
    private /* final */ OutputStream stdin;
    private /* final */ InputStream  stdout;
    private /* final */ InputStream  stderr;
D
duke 已提交
66

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    private static enum LaunchMechanism {
        FORK(1),
        VFORK(3);

        private int value;
        LaunchMechanism(int x) {value = x;}
    };

    /* default is VFORK on Linux */
    private static final LaunchMechanism launchMechanism;
    private static byte[] helperpath;

    private static byte[] toCString(String s) {
        if (s == null)
            return null;
        byte[] bytes = s.getBytes();
        byte[] result = new byte[bytes.length + 1];
        System.arraycopy(bytes, 0,
                         result, 0,
                         bytes.length);
        result[result.length-1] = (byte)0;
        return result;
    }

    static {
        launchMechanism = AccessController.doPrivileged(
                new PrivilegedAction<LaunchMechanism>()
        {
            public LaunchMechanism run() {
                String javahome = System.getProperty("java.home");
                String osArch = System.getProperty("os.arch");

                helperpath = toCString(javahome + "/lib/" + osArch + "/jspawnhelper");
                String s = System.getProperty(
                    "jdk.lang.Process.launchMechanism", "vfork");

                try {
                    return LaunchMechanism.valueOf(s.toUpperCase());
                } catch (IllegalArgumentException e) {
                    throw new Error(s + " is not a supported " +
                        "process launch mechanism on this platform.");
                }
            }
        });
    }

D
duke 已提交
113 114 115
    /* this is for the reaping thread */
    private native int waitForProcessExit(int pid);

116
    /**
117 118 119 120 121
     * Create a process. Depending on the mode flag, this is done by
     * one of the following mechanisms.
     * - fork(2) and exec(2)
     * - clone(2) and exec(2)
     * - vfork(2) and exec(2)
122
     *
123 124 125 126 127 128 129 130 131
     * @param fds an array of three 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.
132 133
     * @return the pid of the subprocess
     */
134 135
    private native int forkAndExec(int mode, byte[] helperpath,
                                   byte[] prog,
136 137 138
                                   byte[] argBlock, int argc,
                                   byte[] envBlock, int envc,
                                   byte[] dir,
139
                                   int[] fds,
140 141
                                   boolean redirectErrorStream)
        throws IOException;
D
duke 已提交
142

143 144 145 146 147
    /**
     * The thread factory used to create "process reaper" daemon threads.
     */
    private static class ProcessReaperThreadFactory implements ThreadFactory {
        private final static ThreadGroup group = getRootThreadGroup();
D
duke 已提交
148

149
        private static ThreadGroup getRootThreadGroup() {
150 151 152 153 154 155 156
            return doPrivileged(new PrivilegedAction<ThreadGroup> () {
                public ThreadGroup run() {
                    ThreadGroup root = Thread.currentThread().getThreadGroup();
                    while (root.getParent() != null)
                        root = root.getParent();
                    return root;
                }});
D
duke 已提交
157 158
        }

159 160 161 162 163 164 165
        public Thread newThread(Runnable grimReaper) {
            // Our thread stack requirement is quite modest.
            Thread t = new Thread(group, grimReaper, "process reaper", 32768);
            t.setDaemon(true);
            // A small attempt (probably futile) to avoid priority inversion
            t.setPriority(Thread.MAX_PRIORITY);
            return t;
D
duke 已提交
166 167 168
        }
    }

169 170 171
    /**
     * The thread pool of "process reaper" daemon threads.
     */
172 173 174 175 176 177
    private static final Executor processReaperExecutor =
        doPrivileged(new PrivilegedAction<Executor>() {
            public Executor run() {
                return Executors.newCachedThreadPool
                    (new ProcessReaperThreadFactory());
            }});
178

D
duke 已提交
179
    UNIXProcess(final byte[] prog,
180 181 182
                final byte[] argBlock, final int argc,
                final byte[] envBlock, final int envc,
                final byte[] dir,
183
                final int[] fds,
184
                final boolean redirectErrorStream)
185 186
            throws IOException {

187 188 189
        pid = forkAndExec(launchMechanism.value,
                          helperpath,
                          prog,
190 191 192 193 194 195 196
                          argBlock, argc,
                          envBlock, envc,
                          dir,
                          fds,
                          redirectErrorStream);

        try {
197
            doPrivileged(new PrivilegedExceptionAction<Void>() {
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
                public Void run() throws IOException {
                    initStreams(fds);
                    return null;
                }});
        } catch (PrivilegedActionException ex) {
            throw (IOException) ex.getException();
        }
    }

    static FileDescriptor newFileDescriptor(int fd) {
        FileDescriptor fileDescriptor = new FileDescriptor();
        fdAccess.set(fileDescriptor, fd);
        return fileDescriptor;
    }

    void initStreams(int[] fds) throws IOException {
        stdin = (fds[0] == -1) ?
            ProcessBuilder.NullOutputStream.INSTANCE :
            new ProcessPipeOutputStream(fds[0]);

        stdout = (fds[1] == -1) ?
            ProcessBuilder.NullInputStream.INSTANCE :
            new ProcessPipeInputStream(fds[1]);

        stderr = (fds[2] == -1) ?
            ProcessBuilder.NullInputStream.INSTANCE :
            new ProcessPipeInputStream(fds[2]);

        processReaperExecutor.execute(new Runnable() {
            public void run() {
                int exitcode = waitForProcessExit(pid);
                UNIXProcess.this.processExited(exitcode);
            }});
    }

233 234 235 236 237 238 239
    void processExited(int exitcode) {
        synchronized (this) {
            this.exitcode = exitcode;
            hasExited = true;
            notifyAll();
        }

240 241 242 243 244 245 246 247
        if (stdout instanceof ProcessPipeInputStream)
            ((ProcessPipeInputStream) stdout).processExited();

        if (stderr instanceof ProcessPipeInputStream)
            ((ProcessPipeInputStream) stderr).processExited();

        if (stdin instanceof ProcessPipeOutputStream)
            ((ProcessPipeOutputStream) stdin).processExited();
D
duke 已提交
248 249 250
    }

    public OutputStream getOutputStream() {
251
        return stdin;
D
duke 已提交
252 253 254
    }

    public InputStream getInputStream() {
255
        return stdout;
D
duke 已提交
256 257 258
    }

    public InputStream getErrorStream() {
259
        return stderr;
D
duke 已提交
260 261 262 263
    }

    public synchronized int waitFor() throws InterruptedException {
        while (!hasExited) {
264 265 266
            wait();
        }
        return exitcode;
D
duke 已提交
267 268
    }

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    @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 已提交
287
    public synchronized int exitValue() {
288 289 290 291
        if (!hasExited) {
            throw new IllegalThreadStateException("process hasn't exited");
        }
        return exitcode;
D
duke 已提交
292 293
    }

294 295
    private static native void destroyProcess(int pid, boolean force);
    private void destroy(boolean force) {
296 297 298 299 300 301 302 303
        // 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.
        synchronized (this) {
            if (!hasExited)
304
                destroyProcess(pid, force);
305
        }
306 307 308
        try { stdin.close();  } catch (IOException ignored) {}
        try { stdout.close(); } catch (IOException ignored) {}
        try { stderr.close(); } catch (IOException ignored) {}
D
duke 已提交
309 310
    }

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    public void destroy() {
        destroy(false);
    }

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

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

326
    private static native void init();
D
duke 已提交
327 328

    static {
329
        init();
D
duke 已提交
330
    }
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

    /**
     * A buffered input stream for a subprocess pipe file descriptor
     * that allows the underlying file descriptor to be reclaimed when
     * the process exits, via the processExited hook.
     *
     * This is tricky because we do not want the user-level InputStream to be
     * closed until the user invokes close(), and we need to continue to be
     * able to read any buffered data lingering in the OS pipe buffer.
     */
    static class ProcessPipeInputStream extends BufferedInputStream {
        ProcessPipeInputStream(int fd) {
            super(new FileInputStream(newFileDescriptor(fd)));
        }

        private static byte[] drainInputStream(InputStream in)
                throws IOException {
            if (in == null) return null;
            int n = 0;
            int j;
            byte[] a = null;
            while ((j = in.available()) > 0) {
                a = (a == null) ? new byte[j] : Arrays.copyOf(a, n + j);
                n += in.read(a, n, j);
            }
            return (a == null || n == a.length) ? a : Arrays.copyOf(a, n);
        }

        /** Called by the process reaper thread when the process exits. */
        synchronized void processExited() {
            // Most BufferedInputStream methods are synchronized, but close()
            // is not, and so we have to handle concurrent racing close().
            try {
                InputStream in = this.in;
                if (in != null) {
                    byte[] stragglers = drainInputStream(in);
                    in.close();
                    this.in = (stragglers == null) ?
                        ProcessBuilder.NullInputStream.INSTANCE :
                        new ByteArrayInputStream(stragglers);
                    if (buf == null) // asynchronous close()?
                        this.in = null;
                }
            } catch (IOException ignored) {
                // probably an asynchronous close().
            }
        }
    }

    /**
     * A buffered output stream for a subprocess pipe file descriptor
     * that allows the underlying file descriptor to be reclaimed when
     * the process exits, via the processExited hook.
     */
    static class ProcessPipeOutputStream extends BufferedOutputStream {
        ProcessPipeOutputStream(int fd) {
            super(new FileOutputStream(newFileDescriptor(fd)));
        }

        /** Called by the process reaper thread when the process exits. */
        synchronized void processExited() {
            OutputStream out = this.out;
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ignored) {
                    // We know of no reason to get an IOException, but if
                    // we do, there's nothing else to do but carry on.
                }
                this.out = ProcessBuilder.NullOutputStream.INSTANCE;
            }
        }
    }
D
duke 已提交
404
}