Runtime.exec()

关于RunTime类的介绍:

 1 /**
 2  * Every Java application has a single instance of class
 3  * <code>Runtime</code> that allows the application to interface with
 4  * the environment in which the application is running. The current
 5  * runtime can be obtained from the <code>getRuntime</code> method.
 6  * <p>
 7  * An application cannot create its own instance of this class.
 8  *
 9  * @author  unascribed
10  * @see     java.lang.Runtime#getRuntime()
11  * @since   JDK1.0
12  */
13
14 public class Runtime {
15     ......
16 }

RunTime类

类具体的定义:

  1 public class Runtime {
  2     private static Runtime currentRuntime = new Runtime();
  3
  4     /**
  5      * Returns the runtime object associated with the current Java application.
  6      * Most of the methods of class <code>Runtime</code> are instance
  7      * methods and must be invoked with respect to the current runtime object.
  8      *
  9      * @return  the <code>Runtime</code> object associated with the current
 10      *          Java application.
 11      */
 12     public static Runtime getRuntime() {
 13         return currentRuntime;
 14     }
 15
 16     /** Don‘t let anyone else instantiate this class */
 17     private Runtime() {}
 18
 19     /**
 20      * Terminates the currently running Java virtual machine by initiating its
 21      * shutdown sequence.  This method never returns normally.  The argument
 22      * serves as a status code; by convention, a nonzero status code indicates
 23      * abnormal termination.
 24      *
 25      * <p> The virtual machine‘s shutdown sequence consists of two phases.  In
 26      * the first phase all registered {@link #addShutdownHook shutdown hooks},
 27      * if any, are started in some unspecified order and allowed to run
 28      * concurrently until they finish.  In the second phase all uninvoked
 29      * finalizers are run if {@link #runFinalizersOnExit finalization-on-exit}
 30      * has been enabled.  Once this is done the virtual machine {@link #halt
 31      * halts}.
 32      *
 33      * <p> If this method is invoked after the virtual machine has begun its
 34      * shutdown sequence then if shutdown hooks are being run this method will
 35      * block indefinitely.  If shutdown hooks have already been run and on-exit
 36      * finalization has been enabled then this method halts the virtual machine
 37      * with the given status code if the status is nonzero; otherwise, it
 38      * blocks indefinitely.
 39      *
 40      * <p> The <tt>{@link System#exit(int) System.exit}</tt> method is the
 41      * conventional and convenient means of invoking this method. <p>
 42      *
 43      * @param  status
 44      *         Termination status.  By convention, a nonzero status code
 45      *         indicates abnormal termination.
 46      *
 47      * @throws SecurityException
 48      *         If a security manager is present and its <tt>{@link
 49      *         SecurityManager#checkExit checkExit}</tt> method does not permit
 50      *         exiting with the specified status
 51      *
 52      * @see java.lang.SecurityException
 53      * @see java.lang.SecurityManager#checkExit(int)
 54      * @see #addShutdownHook
 55      * @see #removeShutdownHook
 56      * @see #runFinalizersOnExit
 57      * @see #halt(int)
 58      */
 59     public void exit(int status) {
 60         SecurityManager security = System.getSecurityManager();
 61         if (security != null) {
 62             security.checkExit(status);
 63         }
 64         Shutdown.exit(status);
 65     }
 66
 67     /**
 68      * Registers a new virtual-machine shutdown hook.
 69      *
 70      * <p> The Java virtual machine <i>shuts down</i> in response to two kinds
 71      * of events:
 72      *
 73      *   <ul>
 74      *
 75      *   <li> The program <i>exits</i> normally, when the last non-daemon
 76      *   thread exits or when the <tt>{@link #exit exit}</tt> (equivalently,
 77      *   {@link System#exit(int) System.exit}) method is invoked, or
 78      *
 79      *   <li> The virtual machine is <i>terminated</i> in response to a
 80      *   user interrupt, such as typing <tt>^C</tt>, or a system-wide event,
 81      *   such as user logoff or system shutdown.
 82      *
 83      *   </ul>
 84      *
 85      * <p> A <i>shutdown hook</i> is simply an initialized but unstarted
 86      * thread.  When the virtual machine begins its shutdown sequence it will
 87      * start all registered shutdown hooks in some unspecified order and let
 88      * them run concurrently.  When all the hooks have finished it will then
 89      * run all uninvoked finalizers if finalization-on-exit has been enabled.
 90      * Finally, the virtual machine will halt.  Note that daemon threads will
 91      * continue to run during the shutdown sequence, as will non-daemon threads
 92      * if shutdown was initiated by invoking the <tt>{@link #exit exit}</tt>
 93      * method.
 94      *
 95      * <p> Once the shutdown sequence has begun it can be stopped only by
 96      * invoking the <tt>{@link #halt halt}</tt> method, which forcibly
 97      * terminates the virtual machine.
 98      *
 99      * <p> Once the shutdown sequence has begun it is impossible to register a
100      * new shutdown hook or de-register a previously-registered hook.
101      * Attempting either of these operations will cause an
102      * <tt>{@link IllegalStateException}</tt> to be thrown.
103      *
104      * <p> Shutdown hooks run at a delicate time in the life cycle of a virtual
105      * machine and should therefore be coded defensively.  They should, in
106      * particular, be written to be thread-safe and to avoid deadlocks insofar
107      * as possible.  They should also not rely blindly upon services that may
108      * have registered their own shutdown hooks and therefore may themselves in
109      * the process of shutting down.  Attempts to use other thread-based
110      * services such as the AWT event-dispatch thread, for example, may lead to
111      * deadlocks.
112      *
113      * <p> Shutdown hooks should also finish their work quickly.  When a
114      * program invokes <tt>{@link #exit exit}</tt> the expectation is
115      * that the virtual machine will promptly shut down and exit.  When the
116      * virtual machine is terminated due to user logoff or system shutdown the
117      * underlying operating system may only allow a fixed amount of time in
118      * which to shut down and exit.  It is therefore inadvisable to attempt any
119      * user interaction or to perform a long-running computation in a shutdown
120      * hook.
121      *
122      * <p> Uncaught exceptions are handled in shutdown hooks just as in any
123      * other thread, by invoking the <tt>{@link ThreadGroup#uncaughtException
124      * uncaughtException}</tt> method of the thread‘s <tt>{@link
125      * ThreadGroup}</tt> object.  The default implementation of this method
126      * prints the exception‘s stack trace to <tt>{@link System#err}</tt> and
127      * terminates the thread; it does not cause the virtual machine to exit or
128      * halt.
129      *
130      * <p> In rare circumstances the virtual machine may <i>abort</i>, that is,
131      * stop running without shutting down cleanly.  This occurs when the
132      * virtual machine is terminated externally, for example with the
133      * <tt>SIGKILL</tt> signal on Unix or the <tt>TerminateProcess</tt> call on
134      * Microsoft Windows.  The virtual machine may also abort if a native
135      * method goes awry by, for example, corrupting internal data structures or
136      * attempting to access nonexistent memory.  If the virtual machine aborts
137      * then no guarantee can be made about whether or not any shutdown hooks
138      * will be run. <p>
139      *
140      * @param   hook
141      *          An initialized but unstarted <tt>{@link Thread}</tt> object
142      *
143      * @throws  IllegalArgumentException
144      *          If the specified hook has already been registered,
145      *          or if it can be determined that the hook is already running or
146      *          has already been run
147      *
148      * @throws  IllegalStateException
149      *          If the virtual machine is already in the process
150      *          of shutting down
151      *
152      * @throws  SecurityException
153      *          If a security manager is present and it denies
154      *          <tt>{@link RuntimePermission}("shutdownHooks")</tt>
155      *
156      * @see #removeShutdownHook
157      * @see #halt(int)
158      * @see #exit(int)
159      * @since 1.3
160      */
161     public void addShutdownHook(Thread hook) {
162         SecurityManager sm = System.getSecurityManager();
163         if (sm != null) {
164             sm.checkPermission(new RuntimePermission("shutdownHooks"));
165         }
166         ApplicationShutdownHooks.add(hook);
167     }
168
169     /**
170      * De-registers a previously-registered virtual-machine shutdown hook. <p>
171      *
172      * @param hook the hook to remove
173      * @return <tt>true</tt> if the specified hook had previously been
174      * registered and was successfully de-registered, <tt>false</tt>
175      * otherwise.
176      *
177      * @throws  IllegalStateException
178      *          If the virtual machine is already in the process of shutting
179      *          down
180      *
181      * @throws  SecurityException
182      *          If a security manager is present and it denies
183      *          <tt>{@link RuntimePermission}("shutdownHooks")</tt>
184      *
185      * @see #addShutdownHook
186      * @see #exit(int)
187      * @since 1.3
188      */
189     public boolean removeShutdownHook(Thread hook) {
190         SecurityManager sm = System.getSecurityManager();
191         if (sm != null) {
192             sm.checkPermission(new RuntimePermission("shutdownHooks"));
193         }
194         return ApplicationShutdownHooks.remove(hook);
195     }
196
197     /**
198      * Forcibly terminates the currently running Java virtual machine.  This
199      * method never returns normally.
200      *
201      * <p> This method should be used with extreme caution.  Unlike the
202      * <tt>{@link #exit exit}</tt> method, this method does not cause shutdown
203      * hooks to be started and does not run uninvoked finalizers if
204      * finalization-on-exit has been enabled.  If the shutdown sequence has
205      * already been initiated then this method does not wait for any running
206      * shutdown hooks or finalizers to finish their work. <p>
207      *
208      * @param  status
209      *         Termination status.  By convention, a nonzero status code
210      *         indicates abnormal termination.  If the <tt>{@link Runtime#exit
211      *         exit}</tt> (equivalently, <tt>{@link System#exit(int)
212      *         System.exit}</tt>) method has already been invoked then this
213      *         status code will override the status code passed to that method.
214      *
215      * @throws SecurityException
216      *         If a security manager is present and its <tt>{@link
217      *         SecurityManager#checkExit checkExit}</tt> method does not permit
218      *         an exit with the specified status
219      *
220      * @see #exit
221      * @see #addShutdownHook
222      * @see #removeShutdownHook
223      * @since 1.3
224      */
225     public void halt(int status) {
226         SecurityManager sm = System.getSecurityManager();
227         if (sm != null) {
228             sm.checkExit(status);
229         }
230         Shutdown.halt(status);
231     }
232
233     /**
234      * Enable or disable finalization on exit; doing so specifies that the
235      * finalizers of all objects that have finalizers that have not yet been
236      * automatically invoked are to be run before the Java runtime exits.
237      * By default, finalization on exit is disabled.
238      *
239      * <p>If there is a security manager,
240      * its <code>checkExit</code> method is first called
241      * with 0 as its argument to ensure the exit is allowed.
242      * This could result in a SecurityException.
243      *
244      * @param value true to enable finalization on exit, false to disable
245      * @deprecated  This method is inherently unsafe.  It may result in
246      *      finalizers being called on live objects while other threads are
247      *      concurrently manipulating those objects, resulting in erratic
248      *      behavior or deadlock.
249      *
250      * @throws  SecurityException
251      *        if a security manager exists and its <code>checkExit</code>
252      *        method doesn‘t allow the exit.
253      *
254      * @see     java.lang.Runtime#exit(int)
255      * @see     java.lang.Runtime#gc()
256      * @see     java.lang.SecurityManager#checkExit(int)
257      * @since   JDK1.1
258      */
259     @Deprecated
260     public static void runFinalizersOnExit(boolean value) {
261         SecurityManager security = System.getSecurityManager();
262         if (security != null) {
263             try {
264                 security.checkExit(0);
265             } catch (SecurityException e) {
266                 throw new SecurityException("runFinalizersOnExit");
267             }
268         }
269         Shutdown.setRunFinalizersOnExit(value);
270     }
271
272     /**
273      * Executes the specified string command in a separate process.
274      *
275      * <p>This is a convenience method.  An invocation of the form
276      * <tt>exec(command)</tt>
277      * behaves in exactly the same way as the invocation
278      * <tt>{@link #exec(String, String[], File) exec}(command, null, null)</tt>.
279      *
280      * @param   command   a specified system command.
281      *
282      * @return  A new {@link Process} object for managing the subprocess
283      *
284      * @throws  SecurityException
285      *          If a security manager exists and its
286      *          {@link SecurityManager#checkExec checkExec}
287      *          method doesn‘t allow creation of the subprocess
288      *
289      * @throws  IOException
290      *          If an I/O error occurs
291      *
292      * @throws  NullPointerException
293      *          If <code>command</code> is <code>null</code>
294      *
295      * @throws  IllegalArgumentException
296      *          If <code>command</code> is empty
297      *
298      * @see     #exec(String[], String[], File)
299      * @see     ProcessBuilder
300      */
301     public Process exec(String command) throws IOException {
302         return exec(command, null, null);
303     }
304
305     /**
306      * Executes the specified string command in a separate process with the
307      * specified environment.
308      *
309      * <p>This is a convenience method.  An invocation of the form
310      * <tt>exec(command, envp)</tt>
311      * behaves in exactly the same way as the invocation
312      * <tt>{@link #exec(String, String[], File) exec}(command, envp, null)</tt>.
313      *
314      * @param   command   a specified system command.
315      *
316      * @param   envp      array of strings, each element of which
317      *                    has environment variable settings in the format
318      *                    <i>name</i>=<i>value</i>, or
319      *                    <tt>null</tt> if the subprocess should inherit
320      *                    the environment of the current process.
321      *
322      * @return  A new {@link Process} object for managing the subprocess
323      *
324      * @throws  SecurityException
325      *          If a security manager exists and its
326      *          {@link SecurityManager#checkExec checkExec}
327      *          method doesn‘t allow creation of the subprocess
328      *
329      * @throws  IOException
330      *          If an I/O error occurs
331      *
332      * @throws  NullPointerException
333      *          If <code>command</code> is <code>null</code>,
334      *          or one of the elements of <code>envp</code> is <code>null</code>
335      *
336      * @throws  IllegalArgumentException
337      *          If <code>command</code> is empty
338      *
339      * @see     #exec(String[], String[], File)
340      * @see     ProcessBuilder
341      */
342     public Process exec(String command, String[] envp) throws IOException {
343         return exec(command, envp, null);
344     }
345
346     /**
347      * Executes the specified string command in a separate process with the
348      * specified environment and working directory.
349      *
350      * <p>This is a convenience method.  An invocation of the form
351      * <tt>exec(command, envp, dir)</tt>
352      * behaves in exactly the same way as the invocation
353      * <tt>{@link #exec(String[], String[], File) exec}(cmdarray, envp, dir)</tt>,
354      * where <code>cmdarray</code> is an array of all the tokens in
355      * <code>command</code>.
356      *
357      * <p>More precisely, the <code>command</code> string is broken
358      * into tokens using a {@link StringTokenizer} created by the call
359      * <code>new {@link StringTokenizer}(command)</code> with no
360      * further modification of the character categories.  The tokens
361      * produced by the tokenizer are then placed in the new string
362      * array <code>cmdarray</code>, in the same order.
363      *
364      * @param   command   a specified system command.
365      *
366      * @param   envp      array of strings, each element of which
367      *                    has environment variable settings in the format
368      *                    <i>name</i>=<i>value</i>, or
369      *                    <tt>null</tt> if the subprocess should inherit
370      *                    the environment of the current process.
371      *
372      * @param   dir       the working directory of the subprocess, or
373      *                    <tt>null</tt> if the subprocess should inherit
374      *                    the working directory of the current process.
375      *
376      * @return  A new {@link Process} object for managing the subprocess
377      *
378      * @throws  SecurityException
379      *          If a security manager exists and its
380      *          {@link SecurityManager#checkExec checkExec}
381      *          method doesn‘t allow creation of the subprocess
382      *
383      * @throws  IOException
384      *          If an I/O error occurs
385      *
386      * @throws  NullPointerException
387      *          If <code>command</code> is <code>null</code>,
388      *          or one of the elements of <code>envp</code> is <code>null</code>
389      *
390      * @throws  IllegalArgumentException
391      *          If <code>command</code> is empty
392      *
393      * @see     ProcessBuilder
394      * @since 1.3
395      */
396     public Process exec(String command, String[] envp, File dir)
397         throws IOException {
398         if (command.length() == 0)
399             throw new IllegalArgumentException("Empty command");
400
401         StringTokenizer st = new StringTokenizer(command);
402         String[] cmdarray = new String[st.countTokens()];
403         for (int i = 0; st.hasMoreTokens(); i++)
404             cmdarray[i] = st.nextToken();
405         return exec(cmdarray, envp, dir);
406     }
407
408     /**
409      * Executes the specified command and arguments in a separate process.
410      *
411      * <p>This is a convenience method.  An invocation of the form
412      * <tt>exec(cmdarray)</tt>
413      * behaves in exactly the same way as the invocation
414      * <tt>{@link #exec(String[], String[], File) exec}(cmdarray, null, null)</tt>.
415      *
416      * @param   cmdarray  array containing the command to call and
417      *                    its arguments.
418      *
419      * @return  A new {@link Process} object for managing the subprocess
420      *
421      * @throws  SecurityException
422      *          If a security manager exists and its
423      *          {@link SecurityManager#checkExec checkExec}
424      *          method doesn‘t allow creation of the subprocess
425      *
426      * @throws  IOException
427      *          If an I/O error occurs
428      *
429      * @throws  NullPointerException
430      *          If <code>cmdarray</code> is <code>null</code>,
431      *          or one of the elements of <code>cmdarray</code> is <code>null</code>
432      *
433      * @throws  IndexOutOfBoundsException
434      *          If <code>cmdarray</code> is an empty array
435      *          (has length <code>0</code>)
436      *
437      * @see     ProcessBuilder
438      */
439     public Process exec(String cmdarray[]) throws IOException {
440         return exec(cmdarray, null, null);
441     }
442
443     /**
444      * Executes the specified command and arguments in a separate process
445      * with the specified environment.
446      *
447      * <p>This is a convenience method.  An invocation of the form
448      * <tt>exec(cmdarray, envp)</tt>
449      * behaves in exactly the same way as the invocation
450      * <tt>{@link #exec(String[], String[], File) exec}(cmdarray, envp, null)</tt>.
451      *
452      * @param   cmdarray  array containing the command to call and
453      *                    its arguments.
454      *
455      * @param   envp      array of strings, each element of which
456      *                    has environment variable settings in the format
457      *                    <i>name</i>=<i>value</i>, or
458      *                    <tt>null</tt> if the subprocess should inherit
459      *                    the environment of the current process.
460      *
461      * @return  A new {@link Process} object for managing the subprocess
462      *
463      * @throws  SecurityException
464      *          If a security manager exists and its
465      *          {@link SecurityManager#checkExec checkExec}
466      *          method doesn‘t allow creation of the subprocess
467      *
468      * @throws  IOException
469      *          If an I/O error occurs
470      *
471      * @throws  NullPointerException
472      *          If <code>cmdarray</code> is <code>null</code>,
473      *          or one of the elements of <code>cmdarray</code> is <code>null</code>,
474      *          or one of the elements of <code>envp</code> is <code>null</code>
475      *
476      * @throws  IndexOutOfBoundsException
477      *          If <code>cmdarray</code> is an empty array
478      *          (has length <code>0</code>)
479      *
480      * @see     ProcessBuilder
481      */
482     public Process exec(String[] cmdarray, String[] envp) throws IOException {
483         return exec(cmdarray, envp, null);
484     }
485
486
487     /**
488      * Executes the specified command and arguments in a separate process with
489      * the specified environment and working directory.
490      *
491      * <p>Given an array of strings <code>cmdarray</code>, representing the
492      * tokens of a command line, and an array of strings <code>envp</code>,
493      * representing "environment" variable settings, this method creates
494      * a new process in which to execute the specified command.
495      *
496      * <p>This method checks that <code>cmdarray</code> is a valid operating
497      * system command.  Which commands are valid is system-dependent,
498      * but at the very least the command must be a non-empty list of
499      * non-null strings.
500      *
501      * <p>If <tt>envp</tt> is <tt>null</tt>, the subprocess inherits the
502      * environment settings of the current process.
503      *
504      * <p>A minimal set of system dependent environment variables may
505      * be required to start a process on some operating systems.
506      * As a result, the subprocess may inherit additional environment variable
507      * settings beyond those in the specified environment.
508      *
509      * <p>{@link ProcessBuilder#start()} is now the preferred way to
510      * start a process with a modified environment.
511      *
512      * <p>The working directory of the new subprocess is specified by <tt>dir</tt>.
513      * If <tt>dir</tt> is <tt>null</tt>, the subprocess inherits the
514      * current working directory of the current process.
515      *
516      * <p>If a security manager exists, its
517      * {@link SecurityManager#checkExec checkExec}
518      * method is invoked with the first component of the array
519      * <code>cmdarray</code> as its argument. This may result in a
520      * {@link SecurityException} being thrown.
521      *
522      * <p>Starting an operating system process is highly system-dependent.
523      * Among the many things that can go wrong are:
524      * <ul>
525      * <li>The operating system program file was not found.
526      * <li>Access to the program file was denied.
527      * <li>The working directory does not exist.
528      * </ul>
529      *
530      * <p>In such cases an exception will be thrown.  The exact nature
531      * of the exception is system-dependent, but it will always be a
532      * subclass of {@link IOException}.
533      *
534      *
535      * @param   cmdarray  array containing the command to call and
536      *                    its arguments.
537      *
538      * @param   envp      array of strings, each element of which
539      *                    has environment variable settings in the format
540      *                    <i>name</i>=<i>value</i>, or
541      *                    <tt>null</tt> if the subprocess should inherit
542      *                    the environment of the current process.
543      *
544      * @param   dir       the working directory of the subprocess, or
545      *                    <tt>null</tt> if the subprocess should inherit
546      *                    the working directory of the current process.
547      *
548      * @return  A new {@link Process} object for managing the subprocess
549      *
550      * @throws  SecurityException
551      *          If a security manager exists and its
552      *          {@link SecurityManager#checkExec checkExec}
553      *          method doesn‘t allow creation of the subprocess
554      *
555      * @throws  IOException
556      *          If an I/O error occurs
557      *
558      * @throws  NullPointerException
559      *          If <code>cmdarray</code> is <code>null</code>,
560      *          or one of the elements of <code>cmdarray</code> is <code>null</code>,
561      *          or one of the elements of <code>envp</code> is <code>null</code>
562      *
563      * @throws  IndexOutOfBoundsException
564      *          If <code>cmdarray</code> is an empty array
565      *          (has length <code>0</code>)
566      *
567      * @see     ProcessBuilder
568      * @since 1.3
569      */
570     public Process exec(String[] cmdarray, String[] envp, File dir)
571         throws IOException {
572         return new ProcessBuilder(cmdarray)
573             .environment(envp)
574             .directory(dir)
575             .start();
576     }
577
578     /**
579      * Returns the number of processors available to the Java virtual machine.
580      *
581      * <p> This value may change during a particular invocation of the virtual
582      * machine.  Applications that are sensitive to the number of available
583      * processors should therefore occasionally poll this property and adjust
584      * their resource usage appropriately. </p>
585      *
586      * @return  the maximum number of processors available to the virtual
587      *          machine; never smaller than one
588      * @since 1.4
589      */
590     public native int availableProcessors();
591
592     /**
593      * Returns the amount of free memory in the Java Virtual Machine.
594      * Calling the
595      * <code>gc</code> method may result in increasing the value returned
596      * by <code>freeMemory.</code>
597      *
598      * @return  an approximation to the total amount of memory currently
599      *          available for future allocated objects, measured in bytes.
600      */
601     public native long freeMemory();
602
603     /**
604      * Returns the total amount of memory in the Java virtual machine.
605      * The value returned by this method may vary over time, depending on
606      * the host environment.
607      * <p>
608      * Note that the amount of memory required to hold an object of any
609      * given type may be implementation-dependent.
610      *
611      * @return  the total amount of memory currently available for current
612      *          and future objects, measured in bytes.
613      */
614     public native long totalMemory();
615
616     /**
617      * Returns the maximum amount of memory that the Java virtual machine will
618      * attempt to use.  If there is no inherent limit then the value {@link
619      * java.lang.Long#MAX_VALUE} will be returned.
620      *
621      * @return  the maximum amount of memory that the virtual machine will
622      *          attempt to use, measured in bytes
623      * @since 1.4
624      */
625     public native long maxMemory();
626
627     /**
628      * Runs the garbage collector.
629      * Calling this method suggests that the Java virtual machine expend
630      * effort toward recycling unused objects in order to make the memory
631      * they currently occupy available for quick reuse. When control
632      * returns from the method call, the virtual machine has made
633      * its best effort to recycle all discarded objects.
634      * <p>
635      * The name <code>gc</code> stands for "garbage
636      * collector". The virtual machine performs this recycling
637      * process automatically as needed, in a separate thread, even if the
638      * <code>gc</code> method is not invoked explicitly.
639      * <p>
640      * The method {@link System#gc()} is the conventional and convenient
641      * means of invoking this method.
642      */
643     public native void gc();
644
645     /* Wormhole for calling java.lang.ref.Finalizer.runFinalization */
646     private static native void runFinalization0();
647
648     /**
649      * Runs the finalization methods of any objects pending finalization.
650      * Calling this method suggests that the Java virtual machine expend
651      * effort toward running the <code>finalize</code> methods of objects
652      * that have been found to be discarded but whose <code>finalize</code>
653      * methods have not yet been run. When control returns from the
654      * method call, the virtual machine has made a best effort to
655      * complete all outstanding finalizations.
656      * <p>
657      * The virtual machine performs the finalization process
658      * automatically as needed, in a separate thread, if the
659      * <code>runFinalization</code> method is not invoked explicitly.
660      * <p>
661      * The method {@link System#runFinalization()} is the conventional
662      * and convenient means of invoking this method.
663      *
664      * @see     java.lang.Object#finalize()
665      */
666     public void runFinalization() {
667         runFinalization0();
668     }
669
670     /**
671      * Enables/Disables tracing of instructions.
672      * If the <code>boolean</code> argument is <code>true</code>, this
673      * method suggests that the Java virtual machine emit debugging
674      * information for each instruction in the virtual machine as it
675      * is executed. The format of this information, and the file or other
676      * output stream to which it is emitted, depends on the host environment.
677      * The virtual machine may ignore this request if it does not support
678      * this feature. The destination of the trace output is system
679      * dependent.
680      * <p>
681      * If the <code>boolean</code> argument is <code>false</code>, this
682      * method causes the virtual machine to stop performing the
683      * detailed instruction trace it is performing.
684      *
685      * @param   on   <code>true</code> to enable instruction tracing;
686      *               <code>false</code> to disable this feature.
687      */
688     public native void traceInstructions(boolean on);
689
690     /**
691      * Enables/Disables tracing of method calls.
692      * If the <code>boolean</code> argument is <code>true</code>, this
693      * method suggests that the Java virtual machine emit debugging
694      * information for each method in the virtual machine as it is
695      * called. The format of this information, and the file or other output
696      * stream to which it is emitted, depends on the host environment. The
697      * virtual machine may ignore this request if it does not support
698      * this feature.
699      * <p>
700      * Calling this method with argument false suggests that the
701      * virtual machine cease emitting per-call debugging information.
702      *
703      * @param   on   <code>true</code> to enable instruction tracing;
704      *               <code>false</code> to disable this feature.
705      */
706     public native void traceMethodCalls(boolean on);
707
708     /**
709      * Loads the native library specified by the filename argument.  The filename
710      * argument must be an absolute path name.
711      * (for example
712      * <code>Runtime.getRuntime().load("/home/avh/lib/libX11.so");</code>).
713      *
714      * If the filename argument, when stripped of any platform-specific library
715      * prefix, path, and file extension, indicates a library whose name is,
716      * for example, L, and a native library called L is statically linked
717      * with the VM, then the JNI_OnLoad_L function exported by the library
718      * is invoked rather than attempting to load a dynamic library.
719      * A filename matching the argument does not have to exist in the file
720      * system. See the JNI Specification for more details.
721      *
722      * Otherwise, the filename argument is mapped to a native library image in
723      * an implementation-dependent manner.
724      * <p>
725      * First, if there is a security manager, its <code>checkLink</code>
726      * method is called with the <code>filename</code> as its argument.
727      * This may result in a security exception.
728      * <p>
729      * This is similar to the method {@link #loadLibrary(String)}, but it
730      * accepts a general file name as an argument rather than just a library
731      * name, allowing any file of native code to be loaded.
732      * <p>
733      * The method {@link System#load(String)} is the conventional and
734      * convenient means of invoking this method.
735      *
736      * @param      filename   the file to load.
737      * @exception  SecurityException  if a security manager exists and its
738      *             <code>checkLink</code> method doesn‘t allow
739      *             loading of the specified dynamic library
740      * @exception  UnsatisfiedLinkError  if either the filename is not an
741      *             absolute path name, the native library is not statically
742      *             linked with the VM, or the library cannot be mapped to
743      *             a native library image by the host system.
744      * @exception  NullPointerException if <code>filename</code> is
745      *             <code>null</code>
746      * @see        java.lang.Runtime#getRuntime()
747      * @see        java.lang.SecurityException
748      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
749      */
750     @CallerSensitive
751     public void load(String filename) {
752         load0(Reflection.getCallerClass(), filename);
753     }
754
755     synchronized void load0(Class<?> fromClass, String filename) {
756         SecurityManager security = System.getSecurityManager();
757         if (security != null) {
758             security.checkLink(filename);
759         }
760         if (!(new File(filename).isAbsolute())) {
761             throw new UnsatisfiedLinkError(
762                 "Expecting an absolute path of the library: " + filename);
763         }
764         ClassLoader.loadLibrary(fromClass, filename, true);
765     }
766
767     /**
768      * Loads the native library specified by the <code>libname</code>
769      * argument.  The <code>libname</code> argument must not contain any platform
770      * specific prefix, file extension or path. If a native library
771      * called <code>libname</code> is statically linked with the VM, then the
772      * JNI_OnLoad_<code>libname</code> function exported by the library is invoked.
773      * See the JNI Specification for more details.
774      *
775      * Otherwise, the libname argument is loaded from a system library
776      * location and mapped to a native library image in an implementation-
777      * dependent manner.
778      * <p>
779      * First, if there is a security manager, its <code>checkLink</code>
780      * method is called with the <code>libname</code> as its argument.
781      * This may result in a security exception.
782      * <p>
783      * The method {@link System#loadLibrary(String)} is the conventional
784      * and convenient means of invoking this method. If native
785      * methods are to be used in the implementation of a class, a standard
786      * strategy is to put the native code in a library file (call it
787      * <code>LibFile</code>) and then to put a static initializer:
788      * <blockquote><pre>
789      * static { System.loadLibrary("LibFile"); }
790      * </pre></blockquote>
791      * within the class declaration. When the class is loaded and
792      * initialized, the necessary native code implementation for the native
793      * methods will then be loaded as well.
794      * <p>
795      * If this method is called more than once with the same library
796      * name, the second and subsequent calls are ignored.
797      *
798      * @param      libname   the name of the library.
799      * @exception  SecurityException  if a security manager exists and its
800      *             <code>checkLink</code> method doesn‘t allow
801      *             loading of the specified dynamic library
802      * @exception  UnsatisfiedLinkError if either the libname argument
803      *             contains a file path, the native library is not statically
804      *             linked with the VM,  or the library cannot be mapped to a
805      *             native library image by the host system.
806      * @exception  NullPointerException if <code>libname</code> is
807      *             <code>null</code>
808      * @see        java.lang.SecurityException
809      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
810      */
811     @CallerSensitive
812     public void loadLibrary(String libname) {
813         loadLibrary0(Reflection.getCallerClass(), libname);
814     }
815
816     synchronized void loadLibrary0(Class<?> fromClass, String libname) {
817         SecurityManager security = System.getSecurityManager();
818         if (security != null) {
819             security.checkLink(libname);
820         }
821         if (libname.indexOf((int)File.separatorChar) != -1) {
822             throw new UnsatisfiedLinkError(
823     "Directory separator should not appear in library name: " + libname);
824         }
825         ClassLoader.loadLibrary(fromClass, libname, false);
826     }
827
828     /**
829      * Creates a localized version of an input stream. This method takes
830      * an <code>InputStream</code> and returns an <code>InputStream</code>
831      * equivalent to the argument in all respects except that it is
832      * localized: as characters in the local character set are read from
833      * the stream, they are automatically converted from the local
834      * character set to Unicode.
835      * <p>
836      * If the argument is already a localized stream, it may be returned
837      * as the result.
838      *
839      * @param      in InputStream to localize
840      * @return     a localized input stream
841      * @see        java.io.InputStream
842      * @see        java.io.BufferedReader#BufferedReader(java.io.Reader)
843      * @see        java.io.InputStreamReader#InputStreamReader(java.io.InputStream)
844      * @deprecated As of JDK&nbsp;1.1, the preferred way to translate a byte
845      * stream in the local encoding into a character stream in Unicode is via
846      * the <code>InputStreamReader</code> and <code>BufferedReader</code>
847      * classes.
848      */
849     @Deprecated
850     public InputStream getLocalizedInputStream(InputStream in) {
851         return in;
852     }
853
854     /**
855      * Creates a localized version of an output stream. This method
856      * takes an <code>OutputStream</code> and returns an
857      * <code>OutputStream</code> equivalent to the argument in all respects
858      * except that it is localized: as Unicode characters are written to
859      * the stream, they are automatically converted to the local
860      * character set.
861      * <p>
862      * If the argument is already a localized stream, it may be returned
863      * as the result.
864      *
865      * @deprecated As of JDK&nbsp;1.1, the preferred way to translate a
866      * Unicode character stream into a byte stream in the local encoding is via
867      * the <code>OutputStreamWriter</code>, <code>BufferedWriter</code>, and
868      * <code>PrintWriter</code> classes.
869      *
870      * @param      out OutputStream to localize
871      * @return     a localized output stream
872      * @see        java.io.OutputStream
873      * @see        java.io.BufferedWriter#BufferedWriter(java.io.Writer)
874      * @see        java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
875      * @see        java.io.PrintWriter#PrintWriter(java.io.OutputStream)
876      */
877     @Deprecated
878     public OutputStream getLocalizedOutputStream(OutputStream out) {
879         return out;
880     }
881
882 }

类的内部定义

RunTime.exec() 用来执行特定的

/**
     * Executes the specified string command in a separate process with the
     * specified environment.
     *

线程阻塞解决

http://zhidao.baidu.com/link?url=lHvJVnZtMWrg-YRdXUKzvXtf6wuldfq2qDGy_JqaRTDmeFG2fL_zZ2mZOS7OEe37i5d9EIFiMAsbySY5xjJnB5keCDxZPwsvYYBPz7IoZH_

时间: 2024-11-07 19:32:57

Runtime.exec()的相关文章

Runtime.exec() sucks!!!!

自己项目中使用到了 Runtime rt = Runtime.getRuntime(); Process p = rt.exec("query session");p.waitFor(); 结果在不同的windows 操作系统中,程序的运行不一致,在windows server 2008上可以很好的运行,但是到了windows7上去卡死了!!!!!!!!!!!!!!!!!!!!!! p.waitFor() 卡死了或者报错: [ERROR] xxxxx Thread-0 - Cannot

为什么Runtime.exec(&quot;ls&quot;)没有任何输出_JAVA基础教程

本文针对为什么Runtime.exec("ls")没有任何输出作出解答,解答如下: 调用Runtime.exec方法将产生一个本地的进程,并返回一个Process子类的实例,该实例可用于控制进程或取得进程的相关信息. 由于调用Runtime.exec方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过Process.getOutputStream(),Process.getInputStream(), Process.getE

使用Runtime.exec()运行windwos dos或linux shell命令

使用Runtime.exec()运行windwos dos或linux shell命令,按实际情况具体测试 实例代码: package com.bookoo.test.command; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter

[转]Java中Runtime.exec的一些事

0 预备知识 1 不正确的调用exitValue 2不正确的调用waitFor 3 一种可接受的调用方式 4 调用认为是可执行程序的时候容易发生的错误 5 window执行的良好示例 6 不良好的重定向命令输出 7 良好的重定向输出示例 8 总结 9 问答 0 预备知识 Runtime类是一个与JVM运行时环境有关的Singleton类,有以下几个值得注意的地方: 0.1 Runtime.getRuntime()可以取得当前JVM的运行时环境,这也是在Java中唯一得到运行时环境的方法. 0.2

java Runtime.exec() 执行问题

Runtime.exec() 不等同于直接执行command line命令! Runtime.exec()很有局限性,对有些命令不能直接把command line里的内容当作String参数传给exec(). 比如重定向等命令.举个例子: javap -l xxx > output.txt 这时要用到exec的第二种重载,即input 参数为String[]: Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh"

64位xp上java Runtime.exec无法正常运行的问题

有一段简单的java代码如下 package com.dongjak.test; import java.io.IOException; public class Test { public static void main(String[] args) { // ProcessUtils.shutdown(1); Runtime runtime = Runtime.getRuntime(); try { runtime.exec("shutdown -f -s -t 1"); } c

Java魔法堂:找外援的利器——Runtime.exec详解

一.前言 Java虽然五脏俱全但总有软肋,譬如获取CPU等硬件信息,当然我们可以通过JNI调用C/C++来获取,但对于对C/C++和Windows API不熟的码农是一系列复杂的学习和踩坑过程.那能不能通过简单一些.学习成本低一些的方式呢?答案是肯定的,在功能实现放在首位的情况下,借他山之石是最简洁有力的做法.而 Runtime.exec方法 就为我们打开这么的一条路了. 二.认识 java.lang.Runtime.exec方法    作用:用于调用外部程序,并重定向外部程序的标准输入.标准输

Java Runtime.exec()的使用

Sun的doc里其实说明还有其他的用法: exec(String[] cmdarray, String[] envp, File dir) Executes the specified command and arguments in a separate process with the specified environment and working directory. 那个dir就是调用的程序的工作目录,这句其实还是很有用的. Windows下调用程序 Process proc =Ru

【解决】OCI runtime exec failed......executable file not found in $PATH&quot;: unknown

[问题]使用docker exec + sh进入容器时报错 [[email protected] home]# docker exec -it container-test bash OCI runtime exec failed: exec failed: container_linux.go:346: starting container process caused "exec: \"bash\": executable file not found in $PATH&