Java Execute Linux command

Source: Internet
Author: User

Transfer from http://blog.csdn.net/a19881029/article/details/8063758

Java programs to execute Linux commands rely primarily on 2 classes: Process and runtime

First look at the process class:

The Processbuilder.start () and Runtime.exec methods create a native process and return an instance of the process subclass that can be  used to control the process and obtain relevant information. The process class provides a way to perform input from the process, perform output to the process, wait for the process to complete,  check the exit status of the process, and destroy (kill) the process.  the method of creating a process may not work well for specific processes on some native platforms, such as native window processes, daemons, Win16/DOS processes  on Microsoft Windows, or shell scripts. The child process created does not have its own terminal or console. All of its standard IO (i.e., stdin, stdout, and stderr)  operations are redirected to the parent process through three streams (Getoutputstream (), getInputStream (), and Geterrorstream ()).  The parent process uses these streams to provide input to the child process and to obtain output from the child process. Because some native platforms only provide a limited buffer size for standard input and output streams,  it can cause child processes to block and even deadlock if the output stream or input stream of a child process fails quickly. When  there are no more references to the process object, instead of deleting the child process, it continues to execute the child process asynchronously.  for Java processes with process objects, it is not necessary to execute the processes represented by the process object asynchronously or concurrently.  

In particular, it is important to note that:

1, the child process created does not have its own terminal console, and all label operations are passed through three streams

(Getoutputstream (), getInputStream (), and Geterrorstream ()) are redirected to the parent process (the parent process can determine the execution of the child process through these flows)

2, because some native platforms only provide a limited buffer size for standard input and output streams, and if the output stream or input stream of the read-write child process fails quickly,

May cause the child process to block, or even create a deadlock

 abstract  void   Destroy () kill the child process.  abstract  int   Exitvalue () returns the exit value of the child process. By convention, a value of 0 indicates a normal termination.            abstract   InputStream Geterrorstream () Gets the error stream for the child process.            abstract   InputStream getInputStream () Gets the input stream of the child process.  abstract   OutputStream Getoutputstream ( ) gets the output stream of the child process.  abstract  int   WaitFor () causes the current thread to wait and, if necessary, waits until the process represented by that process object has been terminated. If the child process has been terminated, this method returns immediately. If the child process is not terminated, the calling thread is blocked until the child process exits. 

It is important to note that if the input stream in the child process is more than the content in the output stream or error stream, it is best to use the cache (note the above Scenario 2)

Look again at the runtime class:

Each Java application has a runtime class instance that enables the application to connect to the environment in which it is running. The current run-time environment can be obtained through the GetRuntime method.   the application cannot create its own instance of the runtime class.  

Introduce several main methods:

Process EXEC            executes the specified string command in a separate process.  process Exec (String command, string[] envp)            executes the specified string command in a separate process in the specified environment.  process Exec (String command, string[] envp, File dir)            executes the specified string command in a separate process with the specified environment and working directory. Process  exec (string[] cmdarray)            executes the specified commands and variables in a separate process.   process exec (string[] cmdarray, string[] envp)            executes the specified commands and variables in a separate process for the specified environment.   process exec (string[] cmdarray, string[] envp, File dir)            executes the specified commands and variables in a separate process for the specified environment and working directory.   

Command: A specified system command.

ENVP: An array of environment variable strings, where each environment variable is formatted as Name=value, or null if the child process should inherit the environment of the current process.

Dir: The working directory of the child process, or null if the child process should inherit the working directory of the current process.

Cmdarray: An array containing the called command and its arguments.

The following are examples (to be executed as executable jar packages thrown into Linux):

 Public classTest { Public Static voidMain (string[] args) {InputStream in=NULL; Try{Process Pro= Runtime.getruntime (). EXEC (Newstring[]{"SH",                                       "/home/test/test.sh", "Select admin from M_admin",                                       "/home/test/result.txt"});              Pro.waitfor (); Inch=Pro.getinputstream (); BufferedReader Read=NewBufferedReader (NewInputStreamReader (in)); String result=Read.readline (); System.out.println ("INFO:" +result); } Catch(Exception e) {e.printstacktrace (); }      }  }  

In this way, process exec (string[] cmdarray) is used.

The/home/test/test.sh script is as follows:

#!/bin/sh    #查询sql  SQL=$1  #查询结果保存文件  result_file=$2  #数据库连接  db_name =Scott  db_pwd=Tiger  db_server=db_test    RESULT= ' Sqlplus-s ${db _name}/${db_pwd}@${db_server}<<!   set heading off  set echo off  0  set feed off    ${sql}  /  commit  /  !  '        ${result} ' >> ${result_file}  0;  

It is important to note that when you need to execute a Linux command with a pipeline (for example: Ps-ef|grep java), it is not possible to use the method above, and the solution is to pass the command that needs to be executed as a parameter to the shell

 Public classTest { Public Static voidMain (string[] args)throwsexception{string[] Cmds= {"/bin/sh", "-C", "Ps-ef|grep Java"}; Process Pro=runtime.getruntime (). exec (CMDS);          Pro.waitfor (); InputStream in=Pro.getinputstream (); BufferedReader Read=NewBufferedReader (NewInputStreamReader (in)); String Line=NULL;  while(line = Read.readline ())! =NULL) {System.out.println (line); }      }  }  

Ps:

Runtime.getruntime (). EXEC () This method of invocation is very resource-intensive in Java virtual machines, even though the command can be executed very quickly, and it is very objective to create a process with frequent calls.

The Java Virtual machine executes this command by first cloning a process that has the same environment variables as the current virtual machine, then executing the external command with the new process and finally exiting the process. Frequent creation consumes a lot of CPU and memory

Java Execute Linux command (GO)

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.