4632N/A/*
4632N/A * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
4632N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4632N/A *
4632N/A * This code is free software; you can redistribute it and/or modify it
4632N/A * under the terms of the GNU General Public License version 2 only, as
4632N/A * published by the Free Software Foundation. Oracle designates this
4632N/A * particular file as subject to the "Classpath" exception as provided
4632N/A * by Oracle in the LICENSE file that accompanied this code.
4632N/A *
4632N/A * This code is distributed in the hope that it will be useful, but WITHOUT
4632N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
4632N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
4632N/A * version 2 for more details (a copy is included in the LICENSE file that
4632N/A * accompanied this code).
4632N/A *
4632N/A * You should have received a copy of the GNU General Public License version
4632N/A * 2 along with this work; if not, write to the Free Software Foundation,
4632N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
4632N/A *
4632N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
4632N/A * or visit www.oracle.com if you need additional information or have any
4632N/A * questions.
4632N/A */
4632N/A
4632N/Apackage java.lang;
4632N/A
4632N/Aimport java.io.BufferedInputStream;
4632N/Aimport java.io.BufferedOutputStream;
4632N/Aimport java.io.ByteArrayInputStream;
4632N/Aimport java.io.FileDescriptor;
4632N/Aimport java.io.FileInputStream;
4632N/Aimport java.io.FileOutputStream;
4632N/Aimport java.io.IOException;
4632N/Aimport java.io.InputStream;
4632N/Aimport java.io.OutputStream;
4632N/Aimport java.util.Arrays;
4632N/Aimport java.util.concurrent.Executors;
4632N/Aimport java.util.concurrent.Executor;
4632N/Aimport java.util.concurrent.ThreadFactory;
4632N/Aimport java.security.AccessController;
4632N/Aimport static java.security.AccessController.doPrivileged;
4632N/Aimport java.security.PrivilegedAction;
4632N/Aimport java.security.PrivilegedActionException;
4632N/Aimport java.security.PrivilegedExceptionAction;
4632N/A
4632N/A/**
4632N/A * java.lang.Process subclass in the UNIX environment.
4632N/A *
4632N/A * @author Mario Wolczko and Ross Knippel.
4632N/A * @author Konstantin Kladko (ported to Bsd)
4632N/A * @author Martin Buchholz
4632N/A */
4632N/Afinal class UNIXProcess extends Process {
4632N/A private static final sun.misc.JavaIOFileDescriptorAccess fdAccess
4632N/A = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess();
4632N/A
4632N/A private final int pid;
4632N/A private int exitcode;
4632N/A private boolean hasExited;
4632N/A
4632N/A private /* final */ OutputStream stdin;
4632N/A private /* final */ InputStream stdout;
4632N/A private /* final */ InputStream stderr;
4632N/A
4632N/A /* this is for the reaping thread */
4632N/A private native int waitForProcessExit(int pid);
4632N/A
4632N/A /**
4632N/A * Create a process using fork(2) and exec(2).
4632N/A *
4632N/A * @param fds an array of three file descriptors.
4632N/A * Indexes 0, 1, and 2 correspond to standard input,
4632N/A * standard output and standard error, respectively. On
4632N/A * input, a value of -1 means to create a pipe to connect
4632N/A * child and parent processes. On output, a value which
4632N/A * is not -1 is the parent pipe fd corresponding to the
4632N/A * pipe which has been created. An element of this array
4632N/A * is -1 on input if and only if it is <em>not</em> -1 on
4632N/A * output.
4632N/A * @return the pid of the subprocess
4632N/A */
4632N/A private native int forkAndExec(byte[] prog,
4632N/A byte[] argBlock, int argc,
4632N/A byte[] envBlock, int envc,
4632N/A byte[] dir,
4632N/A int[] fds,
4632N/A boolean redirectErrorStream)
4632N/A throws IOException;
4632N/A
4632N/A /**
4632N/A * The thread factory used to create "process reaper" daemon threads.
4632N/A */
4632N/A private static class ProcessReaperThreadFactory implements ThreadFactory {
4632N/A private final static ThreadGroup group = getRootThreadGroup();
4632N/A
4632N/A private static ThreadGroup getRootThreadGroup() {
4632N/A return doPrivileged(new PrivilegedAction<ThreadGroup> () {
4632N/A public ThreadGroup run() {
4632N/A ThreadGroup root = Thread.currentThread().getThreadGroup();
4632N/A while (root.getParent() != null)
4632N/A root = root.getParent();
4632N/A return root;
4632N/A }});
4632N/A }
4632N/A
4632N/A public Thread newThread(Runnable grimReaper) {
4632N/A // Our thread stack requirement is quite modest.
4632N/A Thread t = new Thread(group, grimReaper, "process reaper", 32768);
4632N/A t.setDaemon(true);
4632N/A // A small attempt (probably futile) to avoid priority inversion
4632N/A t.setPriority(Thread.MAX_PRIORITY);
4632N/A return t;
4632N/A }
4632N/A }
4632N/A
4632N/A /**
4632N/A * The thread pool of "process reaper" daemon threads.
4632N/A */
4632N/A private static final Executor processReaperExecutor =
4632N/A doPrivileged(new PrivilegedAction<Executor>() {
4632N/A public Executor run() {
4632N/A return Executors.newCachedThreadPool
4632N/A (new ProcessReaperThreadFactory());
4632N/A }});
4632N/A
4632N/A UNIXProcess(final byte[] prog,
4632N/A final byte[] argBlock, final int argc,
4632N/A final byte[] envBlock, final int envc,
4632N/A final byte[] dir,
4632N/A final int[] fds,
4632N/A final boolean redirectErrorStream)
4632N/A throws IOException {
4632N/A
4632N/A pid = forkAndExec(prog,
4632N/A argBlock, argc,
4632N/A envBlock, envc,
4632N/A dir,
4632N/A fds,
4632N/A redirectErrorStream);
4632N/A
4632N/A try {
4632N/A doPrivileged(new PrivilegedExceptionAction<Void>() {
4632N/A public Void run() throws IOException {
4632N/A initStreams(fds);
4632N/A return null;
4632N/A }});
4632N/A } catch (PrivilegedActionException ex) {
4632N/A throw (IOException) ex.getException();
4632N/A }
4632N/A }
4632N/A
4632N/A static FileDescriptor newFileDescriptor(int fd) {
4632N/A FileDescriptor fileDescriptor = new FileDescriptor();
4632N/A fdAccess.set(fileDescriptor, fd);
4632N/A return fileDescriptor;
4632N/A }
4632N/A
4632N/A void initStreams(int[] fds) throws IOException {
4632N/A stdin = (fds[0] == -1) ?
4632N/A ProcessBuilder.NullOutputStream.INSTANCE :
4632N/A new ProcessPipeOutputStream(fds[0]);
4632N/A
4632N/A stdout = (fds[1] == -1) ?
4632N/A ProcessBuilder.NullInputStream.INSTANCE :
4632N/A new ProcessPipeInputStream(fds[1]);
4632N/A
4632N/A stderr = (fds[2] == -1) ?
4632N/A ProcessBuilder.NullInputStream.INSTANCE :
4632N/A new ProcessPipeInputStream(fds[2]);
4632N/A
4632N/A processReaperExecutor.execute(new Runnable() {
4632N/A public void run() {
4632N/A int exitcode = waitForProcessExit(pid);
4632N/A UNIXProcess.this.processExited(exitcode);
4632N/A }});
4632N/A }
4632N/A
4632N/A void processExited(int exitcode) {
4632N/A synchronized (this) {
4632N/A this.exitcode = exitcode;
4632N/A hasExited = true;
4632N/A notifyAll();
4632N/A }
4632N/A
4632N/A if (stdout instanceof ProcessPipeInputStream)
4632N/A ((ProcessPipeInputStream) stdout).processExited();
4632N/A
4632N/A if (stderr instanceof ProcessPipeInputStream)
4632N/A ((ProcessPipeInputStream) stderr).processExited();
4632N/A
4632N/A if (stdin instanceof ProcessPipeOutputStream)
4632N/A ((ProcessPipeOutputStream) stdin).processExited();
4632N/A }
4632N/A
4632N/A public OutputStream getOutputStream() {
4632N/A return stdin;
4632N/A }
4632N/A
4632N/A public InputStream getInputStream() {
4632N/A return stdout;
4632N/A }
4632N/A
4632N/A public InputStream getErrorStream() {
4632N/A return stderr;
4632N/A }
4632N/A
4632N/A public synchronized int waitFor() throws InterruptedException {
4632N/A while (!hasExited) {
4632N/A wait();
4632N/A }
4632N/A return exitcode;
4632N/A }
4632N/A
4632N/A public synchronized int exitValue() {
4632N/A if (!hasExited) {
4632N/A throw new IllegalThreadStateException("process hasn't exited");
4632N/A }
4632N/A return exitcode;
4632N/A }
4632N/A
4632N/A private static native void destroyProcess(int pid);
4632N/A public void destroy() {
4632N/A // There is a risk that pid will be recycled, causing us to
4632N/A // kill the wrong process! So we only terminate processes
4632N/A // that appear to still be running. Even with this check,
4632N/A // there is an unavoidable race condition here, but the window
4632N/A // is very small, and OSes try hard to not recycle pids too
4632N/A // soon, so this is quite safe.
4632N/A synchronized (this) {
4632N/A if (!hasExited)
4632N/A destroyProcess(pid);
4632N/A }
4632N/A try { stdin.close(); } catch (IOException ignored) {}
4632N/A try { stdout.close(); } catch (IOException ignored) {}
4632N/A try { stderr.close(); } catch (IOException ignored) {}
4632N/A }
4632N/A
4632N/A /* This routine initializes JNI field offsets for the class */
4632N/A private static native void initIDs();
4632N/A
4632N/A static {
4632N/A initIDs();
4632N/A }
4632N/A
4632N/A /**
4632N/A * A buffered input stream for a subprocess pipe file descriptor
4632N/A * that allows the underlying file descriptor to be reclaimed when
4632N/A * the process exits, via the processExited hook.
4632N/A *
4632N/A * This is tricky because we do not want the user-level InputStream to be
4632N/A * closed until the user invokes close(), and we need to continue to be
4632N/A * able to read any buffered data lingering in the OS pipe buffer.
4632N/A */
4632N/A static class ProcessPipeInputStream extends BufferedInputStream {
4632N/A ProcessPipeInputStream(int fd) {
4632N/A super(new FileInputStream(newFileDescriptor(fd)));
4632N/A }
4632N/A
4632N/A private static byte[] drainInputStream(InputStream in)
4632N/A throws IOException {
4632N/A if (in == null) return null;
4632N/A int n = 0;
4632N/A int j;
4632N/A byte[] a = null;
4632N/A while ((j = in.available()) > 0) {
4632N/A a = (a == null) ? new byte[j] : Arrays.copyOf(a, n + j);
4632N/A n += in.read(a, n, j);
4632N/A }
4632N/A return (a == null || n == a.length) ? a : Arrays.copyOf(a, n);
4632N/A }
4632N/A
4632N/A /** Called by the process reaper thread when the process exits. */
4632N/A synchronized void processExited() {
4632N/A // Most BufferedInputStream methods are synchronized, but close()
4632N/A // is not, and so we have to handle concurrent racing close().
4632N/A try {
4632N/A InputStream in = this.in;
4632N/A if (in != null) {
4632N/A byte[] stragglers = drainInputStream(in);
4632N/A in.close();
4632N/A this.in = (stragglers == null) ?
4632N/A ProcessBuilder.NullInputStream.INSTANCE :
4632N/A new ByteArrayInputStream(stragglers);
4632N/A if (buf == null) // asynchronous close()?
4632N/A this.in = null;
4632N/A }
4632N/A } catch (IOException ignored) {
4632N/A // probably an asynchronous close().
4632N/A }
4632N/A }
4632N/A }
4632N/A
4632N/A /**
4632N/A * A buffered output stream for a subprocess pipe file descriptor
4632N/A * that allows the underlying file descriptor to be reclaimed when
4632N/A * the process exits, via the processExited hook.
4632N/A */
4632N/A static class ProcessPipeOutputStream extends BufferedOutputStream {
4632N/A ProcessPipeOutputStream(int fd) {
4632N/A super(new FileOutputStream(newFileDescriptor(fd)));
4632N/A }
4632N/A
4632N/A /** Called by the process reaper thread when the process exits. */
4632N/A synchronized void processExited() {
4632N/A OutputStream out = this.out;
4632N/A if (out != null) {
4632N/A try {
4632N/A out.close();
4632N/A } catch (IOException ignored) {
4632N/A // We know of no reason to get an IOException, but if
4632N/A // we do, there's nothing else to do but carry on.
4632N/A }
4632N/A this.out = ProcessBuilder.NullOutputStream.INSTANCE;
4632N/A }
4632N/A }
4632N/A }
4632N/A}