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