Java calls shell Script blocking

Source: Internet
Author: User

Java when invoking the shell, to continuously read the process of the standard output and error output stream information, or the buffer is full of the child process will be blocked and can not continue to run, up to two threads continuously read standard output, error flow information without being blocked

Import java.io.bufferedreader;import java.io.ioexception;import java.io.inputstream;import  java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import  java.nio.charset.charset;import org.apache.commons.io.ioutils;import ch.ethz.ssh2.channelcondition; Import ch.ethz.ssh2.connection;import ch.ethz.ssh2.session;public class rmtshellexecutor  {private connection conn;private string ip;private string usr;private  string psword;private string charset = charset.defaultcharset (). toString (); Private static final int time_out = 1000 * 5 * 60;public  rmtshellexecutor (STRING IP, STRING USR, STRING PS)  {this.ip = ip ; this.usr = usr;this.psword = ps;} Private boolean login ()  throws ioexception {conn = new connection (IP); conn.connect (); Return conn.authenticatewithpassword (Usr, psword);} Local execution Method Public static void execlocal (string cmd)  {        try {process proc = runtime.getruntime (). exec (CMD); Streamgobbler errorgobbler = new streamgobbler (Proc.geterrorstream (),  "ERROR"); Streamgobbler outputgobbler = new streamgobbler (Proc.getinputstream (),  "OUTPUT"); Errorgobbler.start (); Outputgobbler.start (); Int exitval = proc.waitfor ();         system.out.println ("exitvalue: "  + exitval);      } catch  (exception e)  {  e.printstacktrace ();      } }            //Remote Execution method public  int execremote (STRING CMDS) {inputstream stdout = null;inputstream stderr = null;int ret = -1;try {if  (Login ())  {// Open a  new {@link  Session} on this connectionSession session =  Conn.opensession ();// execute a command on the remote  Machine.session.execCommand (CMDS); Gobblerthread gtout = new gobblerthread (Session.getstdout (), "STD_OUT"); Gobblerthread gterr = new gobblerthread (Session.getstderr (), "STD_ERR"); GtOut.start (); Gterr.start (); Session.waitforcondition (channelcondition.exit_status, time_out);ret =  Session.getexitstatus ();}  else {}}catch (exception e) {e.printstacktrace ();} finally {if  (Conn != null)  {conn.close ();} ioutils.closequietly (StdOut); ioutils.closequietly (STDERR);} Return ret;} Public static void main (string args[])  throws exception {rmtshellexecutor  exe = new&nbsP Rmtshellexecutor ("192.168.3.5",  "Test", "123456"); System.out.println (Exe.execremote ("sh /home/test/cmd.sh company=32"));}} class gobblerthread extends thread{    inputstream is;     string type;        gobblerthread (InputStream is ,  string type)     {        this.is  = is;        this.type = type;    }         public void run ()     {         try        {             InputStreamReader isr = new  InputStreamReader (is);             bufferedreadEr br = new bufferedreader (ISR);             String line=null;             while  (  (Line = br.readline ())  != null)                  system.out.println (line);                 } catch  (IOException  e)               {                 e.printstacktrace ();                 }     }}

Execlocal method for calling cmd locally

Exeremote the method of using SSH to log on to the remote machine to invoke CMD


Reference article: http://www.linuxidc.com/Linux/2014-04/99557.htm

This article from the "Down-to-earth, look at the Stars" blog, please be sure to keep this source http://xubcing.blog.51cto.com/3502962/1660692

Java calls shell Script blocking

Related Article

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.