src/solaris/classes/java/lang/UNIXProcess.java.linux

Print this page




  46 
  47 /**
  48  * java.lang.Process subclass in the UNIX environment.
  49  *
  50  * @author Mario Wolczko and Ross Knippel.
  51  * @author Konstantin Kladko (ported to Linux)
  52  * @author Martin Buchholz
  53  */
  54 final class UNIXProcess extends Process {
  55     private static final sun.misc.JavaIOFileDescriptorAccess fdAccess
  56         = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess();
  57 
  58     private final int pid;
  59     private int exitcode;
  60     private boolean hasExited;
  61 
  62     private /* final */ OutputStream stdin;
  63     private /* final */ InputStream  stdout;
  64     private /* final */ InputStream  stderr;
  65 














































  66     /* this is for the reaping thread */
  67     private native int waitForProcessExit(int pid);
  68 
  69     /**
  70      * Create a process using fork(2) and exec(2).




  71      *
  72      * @param fds an array of three file descriptors.
  73      *        Indexes 0, 1, and 2 correspond to standard input,
  74      *        standard output and standard error, respectively.  On
  75      *        input, a value of -1 means to create a pipe to connect
  76      *        child and parent processes.  On output, a value which
  77      *        is not -1 is the parent pipe fd corresponding to the
  78      *        pipe which has been created.  An element of this array
  79      *        is -1 on input if and only if it is <em>not</em> -1 on
  80      *        output.
  81      * @return the pid of the subprocess
  82      */
  83     private native int forkAndExec(byte[] prog,

  84                                    byte[] argBlock, int argc,
  85                                    byte[] envBlock, int envc,
  86                                    byte[] dir,
  87                                    int[] fds,
  88                                    boolean redirectErrorStream)
  89         throws IOException;
  90 
  91     /**
  92      * The thread factory used to create "process reaper" daemon threads.
  93      */
  94     private static class ProcessReaperThreadFactory implements ThreadFactory {
  95         private final static ThreadGroup group = getRootThreadGroup();
  96 
  97         private static ThreadGroup getRootThreadGroup() {
  98             return doPrivileged(new PrivilegedAction<ThreadGroup> () {
  99                 public ThreadGroup run() {
 100                     ThreadGroup root = Thread.currentThread().getThreadGroup();
 101                     while (root.getParent() != null)
 102                         root = root.getParent();
 103                     return root;


 115     }
 116 
 117     /**
 118      * The thread pool of "process reaper" daemon threads.
 119      */
 120     private static final Executor processReaperExecutor =
 121         doPrivileged(new PrivilegedAction<Executor>() {
 122             public Executor run() {
 123                 return Executors.newCachedThreadPool
 124                     (new ProcessReaperThreadFactory());
 125             }});
 126 
 127     UNIXProcess(final byte[] prog,
 128                 final byte[] argBlock, final int argc,
 129                 final byte[] envBlock, final int envc,
 130                 final byte[] dir,
 131                 final int[] fds,
 132                 final boolean redirectErrorStream)
 133             throws IOException {
 134 
 135         pid = forkAndExec(prog,


 136                           argBlock, argc,
 137                           envBlock, envc,
 138                           dir,
 139                           fds,
 140                           redirectErrorStream);
 141 
 142         try {
 143             doPrivileged(new PrivilegedExceptionAction<Void>() {
 144                 public Void run() throws IOException {
 145                     initStreams(fds);
 146                     return null;
 147                 }});
 148         } catch (PrivilegedActionException ex) {
 149             throw (IOException) ex.getException();
 150         }
 151     }
 152 
 153     static FileDescriptor newFileDescriptor(int fd) {
 154         FileDescriptor fileDescriptor = new FileDescriptor();
 155         fdAccess.set(fileDescriptor, fd);


 219         return exitcode;
 220     }
 221 
 222     private static native void destroyProcess(int pid);
 223     public void destroy() {
 224         // There is a risk that pid will be recycled, causing us to
 225         // kill the wrong process!  So we only terminate processes
 226         // that appear to still be running.  Even with this check,
 227         // there is an unavoidable race condition here, but the window
 228         // is very small, and OSes try hard to not recycle pids too
 229         // soon, so this is quite safe.
 230         synchronized (this) {
 231             if (!hasExited)
 232                 destroyProcess(pid);
 233         }
 234         try { stdin.close();  } catch (IOException ignored) {}
 235         try { stdout.close(); } catch (IOException ignored) {}
 236         try { stderr.close(); } catch (IOException ignored) {}
 237     }
 238 
 239     /* This routine initializes JNI field offsets for the class */
 240     private static native void initIDs();
 241 
 242     static {
 243         initIDs();
 244     }
 245 
 246     /**
 247      * A buffered input stream for a subprocess pipe file descriptor
 248      * that allows the underlying file descriptor to be reclaimed when
 249      * the process exits, via the processExited hook.
 250      *
 251      * This is tricky because we do not want the user-level InputStream to be
 252      * closed until the user invokes close(), and we need to continue to be
 253      * able to read any buffered data lingering in the OS pipe buffer.
 254      */
 255     static class ProcessPipeInputStream extends BufferedInputStream {
 256         ProcessPipeInputStream(int fd) {
 257             super(new FileInputStream(newFileDescriptor(fd)));
 258         }
 259 
 260         private static byte[] drainInputStream(InputStream in)
 261                 throws IOException {
 262             if (in == null) return null;
 263             int n = 0;




  46 
  47 /**
  48  * java.lang.Process subclass in the UNIX environment.
  49  *
  50  * @author Mario Wolczko and Ross Knippel.
  51  * @author Konstantin Kladko (ported to Linux)
  52  * @author Martin Buchholz
  53  */
  54 final class UNIXProcess extends Process {
  55     private static final sun.misc.JavaIOFileDescriptorAccess fdAccess
  56         = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess();
  57 
  58     private final int pid;
  59     private int exitcode;
  60     private boolean hasExited;
  61 
  62     private /* final */ OutputStream stdin;
  63     private /* final */ InputStream  stdout;
  64     private /* final */ InputStream  stderr;
  65 
  66     private static enum LaunchMechanism {
  67         FORK(1),
  68         VFORK(3);
  69 
  70         private int value;
  71         LaunchMechanism(int x) {value = x;}
  72     };
  73 
  74     /* default is VFORK on Linux */
  75     private static final LaunchMechanism launchMechanism;
  76     private static byte[] helperpath;
  77 
  78     private static byte[] toCString(String s) {
  79         if (s == null)
  80             return null;
  81         byte[] bytes = s.getBytes();
  82         byte[] result = new byte[bytes.length + 1];
  83         System.arraycopy(bytes, 0,
  84                          result, 0,
  85                          bytes.length);
  86         result[result.length-1] = (byte)0;
  87         return result;
  88     }
  89 
  90     static {
  91         launchMechanism = AccessController.doPrivileged(
  92                 new PrivilegedAction<LaunchMechanism>()
  93         {
  94             public LaunchMechanism run() {
  95                 String javahome = System.getProperty("java.home");
  96                 String osArch = System.getProperty("os.arch");
  97 
  98                 helperpath = toCString(javahome + "/lib/" + osArch + "/jspawnhelper");
  99                 String s = System.getProperty(
 100                     "jdk.lang.Process.launchMechanism", "vfork");
 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      * - clone(2) and exec(2)
 120      * - vfork(2) and exec(2)
 121      *
 122      * @param fds an array of three file descriptors.
 123      *        Indexes 0, 1, and 2 correspond to standard input,
 124      *        standard output and standard error, respectively.  On
 125      *        input, a value of -1 means to create a pipe to connect
 126      *        child and parent processes.  On output, a value which
 127      *        is not -1 is the parent pipe fd corresponding to the
 128      *        pipe which has been created.  An element of this array
 129      *        is -1 on input if and only if it is <em>not</em> -1 on
 130      *        output.
 131      * @return the pid of the subprocess
 132      */
 133     private native int forkAndExec(int mode, byte[] helperpath,
 134                                    byte[] prog,
 135                                    byte[] argBlock, int argc,
 136                                    byte[] envBlock, int envc,
 137                                    byte[] dir,
 138                                    int[] fds,
 139                                    boolean redirectErrorStream)
 140         throws IOException;
 141 
 142     /**
 143      * The thread factory used to create "process reaper" daemon threads.
 144      */
 145     private static class ProcessReaperThreadFactory implements ThreadFactory {
 146         private final static ThreadGroup group = getRootThreadGroup();
 147 
 148         private static ThreadGroup getRootThreadGroup() {
 149             return doPrivileged(new PrivilegedAction<ThreadGroup> () {
 150                 public ThreadGroup run() {
 151                     ThreadGroup root = Thread.currentThread().getThreadGroup();
 152                     while (root.getParent() != null)
 153                         root = root.getParent();
 154                     return root;


 166     }
 167 
 168     /**
 169      * The thread pool of "process reaper" daemon threads.
 170      */
 171     private static final Executor processReaperExecutor =
 172         doPrivileged(new PrivilegedAction<Executor>() {
 173             public Executor run() {
 174                 return Executors.newCachedThreadPool
 175                     (new ProcessReaperThreadFactory());
 176             }});
 177 
 178     UNIXProcess(final byte[] prog,
 179                 final byte[] argBlock, final int argc,
 180                 final byte[] envBlock, final int envc,
 181                 final byte[] dir,
 182                 final int[] fds,
 183                 final boolean redirectErrorStream)
 184             throws IOException {
 185 
 186         pid = forkAndExec(launchMechanism.value,
 187                           helperpath,
 188                           prog,
 189                           argBlock, argc,
 190                           envBlock, envc,
 191                           dir,
 192                           fds,
 193                           redirectErrorStream);
 194 
 195         try {
 196             doPrivileged(new PrivilegedExceptionAction<Void>() {
 197                 public Void run() throws IOException {
 198                     initStreams(fds);
 199                     return null;
 200                 }});
 201         } catch (PrivilegedActionException ex) {
 202             throw (IOException) ex.getException();
 203         }
 204     }
 205 
 206     static FileDescriptor newFileDescriptor(int fd) {
 207         FileDescriptor fileDescriptor = new FileDescriptor();
 208         fdAccess.set(fileDescriptor, fd);


 272         return exitcode;
 273     }
 274 
 275     private static native void destroyProcess(int pid);
 276     public void destroy() {
 277         // There is a risk that pid will be recycled, causing us to
 278         // kill the wrong process!  So we only terminate processes
 279         // that appear to still be running.  Even with this check,
 280         // there is an unavoidable race condition here, but the window
 281         // is very small, and OSes try hard to not recycle pids too
 282         // soon, so this is quite safe.
 283         synchronized (this) {
 284             if (!hasExited)
 285                 destroyProcess(pid);
 286         }
 287         try { stdin.close();  } catch (IOException ignored) {}
 288         try { stdout.close(); } catch (IOException ignored) {}
 289         try { stderr.close(); } catch (IOException ignored) {}
 290     }
 291 
 292     private static native void init();

 293 
 294     static {
 295         init();
 296     }
 297 
 298     /**
 299      * A buffered input stream for a subprocess pipe file descriptor
 300      * that allows the underlying file descriptor to be reclaimed when
 301      * the process exits, via the processExited hook.
 302      *
 303      * This is tricky because we do not want the user-level InputStream to be
 304      * closed until the user invokes close(), and we need to continue to be
 305      * able to read any buffered data lingering in the OS pipe buffer.
 306      */
 307     static class ProcessPipeInputStream extends BufferedInputStream {
 308         ProcessPipeInputStream(int fd) {
 309             super(new FileInputStream(newFileDescriptor(fd)));
 310         }
 311 
 312         private static byte[] drainInputStream(InputStream in)
 313                 throws IOException {
 314             if (in == null) return null;
 315             int n = 0;