[Android] [Java] Sharing Process execution Command line encapsulation class

Source: Internet
Author: User

As mentioned in the previous article, the inability to create a process occurs when you create too many command-line statements with the Java creation process.

[Android] Processbuilder and Runtime.getruntime (). exec separate creation process differences

After several tests, it was found that there was no normal exit process, and the problem was caused by a full read of the streaming data and the shutdown stream.

After several optimizations, the following encapsulation classes are established:

Processmodel.java

Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import java.io.outputstream;/** * Create by Qiujuer * 2014-07-26 * <p/> * Execute command line statements static method encapsulation */    public class ProcessModel {//Line break private static final String break_line;    Execute exit command private static final byte[] Command_exit;    Error buffer private static byte[] buffer;        /** * Static variable initialization */static {break_line = "\ n";        Command_exit = "\nexit\n". GetBytes ();    BUFFER = new BYTE[32]; }/** * Execute command * * @param params command parameter * <pre> eg: "/system/bin/ping", "-C", "4", "-S"        , "$", "www.qiujuer.net" </pre> * @return Execution result */public static String execute (String ... params) {        Process process = NULL;        StringBuilder sbreader = null;        BufferedReader breader = null;        InputStreamReader isreader = null;        InputStream in = null;        InputStream err = null; OutputstReam out = null;            try {process = new Processbuilder (). command (params). Start ();            out = Process.getoutputstream ();            in = Process.getinputstream ();            Err = Process.geterrorstream ();            Out.write (Command_exit);            Out.flush ();            Process.waitfor ();            Isreader = new InputStreamReader (in);            Breader = new BufferedReader (Isreader);            String s;                if ((s = breader.readline ()) = null) {Sbreader = new StringBuilder ();                Sbreader.append (s);                Sbreader.append (Break_line);                    while ((s = breader.readline ()) = null) {sbreader.append (s);                Sbreader.append (Break_line); }} while ((Err.read (BUFFER)) > 0) {}} catch (IOException e) {E.P        Rintstacktrace (); } catch (Exception e) {E.PRIntstacktrace ();            } finally {Closeallstream (out, err, in, Isreader, Breader);                if (process! = null) {Processdestroy (process);            Process = NULL;        }} if (Sbreader = = null) return null;    else return sbreader.tostring (); }/** * Close all streams * * @param out output stream * @param err Error stream * @param in input stream * @param isre Ader Input Stream Encapsulation * @param breader input Stream encapsulated */private static void Closeallstream (OutputStream out, InputStream err, INP                Utstream in, InputStreamReader Isreader, BufferedReader breader) {if (out! = null) try {            Out.close ();            } catch (IOException e) {e.printstacktrace ();            } if (err! = null) try {err.close ();            } catch (IOException e) {e.printstacktrace ();          } if (in = null) try {      In.close ();            } catch (IOException e) {e.printstacktrace ();            } if (Isreader! = null) try {isreader.close ();            } catch (IOException e) {e.printstacktrace ();            } if (Breader! = null) try {breader.close ();            } catch (IOException e) {e.printstacktrace (); }}/** * through the android underlying implementation process shutdown * * @param process Progress */private static void KillProcess (Process proc        ESS) {int PID = GETPROCESSID (process);             if (pid! = 0) {try {//android kill process android.os.Process.killProcess (PID);                } catch (Exception e) {try {Process.destroy ();     } catch (Exception ex) {}}}/** * Get the ID of the process * * @param process * @return */private static int GETPROCESSID (Process process) {String str = process.tostring ();            try {int i = str.indexof ("=") + 1;            Int J = str.indexof ("]");            str = str.substring (i, j);        return Integer.parseint (str);        } catch (Exception e) {return 0;        }}/** * Destroy process * * @param process Progress */private static void Processdestroy (process process) {                    if (process! = null) {try {//To determine if the normal exit if (Process.exitvalue ()! = 0) {                KillProcess (process);            }} catch (Illegalthreadstateexception e) {killprocess (process); }        }    }}

This issue does not occur when a batch stress test arrives at 125,643 threads, and is hereby shared with you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.