您的位置:首页 > 运维架构 > Shell

如何在java程序中调用linux命令或者shell脚本

2019-05-03 15:25 483 查看
               

http://blog.sina.com.cn/s/blog_6433391301019bpn.html

http://blog.csdn.net/moreorless/article/details/4182883

在java程序中如何调用linux的命令?如何调用shell脚本呢?

这里不得不提到java的process类了。

process这个类是一个抽象类,封装了一个进程(你在调用linux的命令或者shell脚本就是为了执行一个在linux下执行的程序,所以应该使用process类)。

process类提供了执行从进程输入,执行输出到进程,等待进程完成,检查进程的推出状态,以及shut down掉进程。


至于详细的process类的介绍放在以后介绍。

另外还要注意一个类:Runtime类,Runtime类是一个与JVM运行时环境有关的类,这个类是Singleton的。

这里用到的Runtime.getRuntime()方法是取得当前JVM的运行环境,也是java中唯一可以得到运行环境的方法。(另外,Runtime的大部分方法都是实例方法,也就是说每次运行调用的时候都需要调用到getRuntime方法)

下面说说Runtime的exec()方法,这里要注意的有一点,就是public Process exec(String [] cmdArray, String [] envp);这个方法中cmdArray是一个执行的命令和参数的字符串数组,数组的第一个元素是要执行的命令往后依次都是命令的参数,envp感觉应该和C中的execve中的环境变量是一样的,envp中使用的是name=value的方式。

下面说一下,如何使用process来调用shell脚本

例如,我需要在linux下实行linux命令:sh test.sh,下面就是执行test.sh命令的方法:

这个var参数就是日期这个201102包的名字。

    String shpath="/test/test.sh";   //程序路径

    Process process =null;

    String command1 = “chmod 777 ” + shpath;
    process = Runtime.getRuntime().exec(command1);
    process.waitFor();




    String var="201102";               //参数

    String command2 = “/bin/sh ” + shpath + ” ” + var; 
    Runtime.getRuntime().exec(command2).waitFor();

注意:

1

我为什么要使用 chmod 777命令呢?在有的机器上面,可能没有设置权限问题。这是你在linux下面执行shell脚本需要注意的问题。没有的话,就需要添加权限,就用chmod 777,否则在执行到Runtime.getRuntime().exec的时侯会出现Permission denied错误。

2

waitFor()这个也是必不可缺的,如果你需要执行多行命令的话,把waitFor()这个加上。



---------------

有时,我们需要在java程序中调用外部程序,我们可用通过Runtime.exec()调用来完成。

 

 

The class 

java.lang.Runtime
 features a static method called 
getRuntime()
, which retrieves the current Java Runtime Environment. That is the only way to obtain a reference to the 
Runtime
 object. With that reference, you can run external programs by invoking the 
Runtime
 class's 
exec()
 method. Developers often call this method to launch a browser for displaying a help page in HTML.

 

exec()有四个重载版本

There are four overloaded versions of the 

exec()
 command:

  • public Process exec(String command);
  • public Process exec(String [] cmdArray);
  • public Process exec(String command, String [] envp);
  • public Process exec(String [] cmdArray, String [] envp);

 

For each of these methods, a command -- and possibly a set of arguments -- is passed to an operating-system-specific function call. This subsequently creates an operating-system-specific process (a running program) with a reference to a 

Process
 class returned to the Java VM. The 
Process
 class is an abstract class, because a specific subclass of 
Process
 exists for each operating system.

You can pass three possible input parameters into these methods:

  1. A single string that represents both the program to execute and any arguments to that program
  2. An array of strings that separate the program from its arguments
  3. An array of environment variables

Pass in the environment variables in the form 

name=value
. If you use the version of 
exec()
 with a single string for both the program and its arguments, note that the string is parsed using white space as the delimiter via the 
StringTokenizer
 class.

 

注意事项:

1.  当调用的外部命令中包含重定向(<、>),管道( | ) 命令时,exec(String command)的版本不能正确解析重定向、管道操作符。所以需要使用exec(String [] cmdArray)。

   如, echo "hello world" > /home/admin/newFile.txt

       ls -e | grep java

   需要使用如下的调用方式

       String []cmdArray = new String[]{ "/bin/sh", "-c", "ls -e | grep java"};

             Runtime.getRuntime().exec(cmdArray);

 

2.  

    

永远要在调用waitFor()方法之前读取数据流永远要先从标准错误流中读取,然后再读取标准输出流

 

The next version of Savant is going to focus heavily on the stand-alone runtime and support for dialects and plugins. Supporting all that is largely handled by using a simple executor framework I wrote around Java 1.4 and lower’s Runtime.exec method. A few things to keep in mind when using this:

  1. Always read from the streams prior to calling waitFor. Otherwise you could end up waiting forever on Windows and other OS platforms whose I/O buffers can’t store enough from standard out and standard error to ensure the program has finished. These platforms will pause the execution of whatever is running until something reads the buffered content from standard out and standard error. I would imagine all platforms suffer from this, but some platforms have larger buffers than others. Needless to say, always read from the streams first.
  2. Always read from standard error first. I ran across a bug where some OS platforms will always open standard out, but never close it. What this means is that if you read from standard out first and the process only writes to standard error, you’ll hang forever waiting to read. If you read from standard error first, you’ll always be okay on these platforms because the OS seems to shutdown standard error. I think however, that the best way to handle all cases is to check both standard error and standard out for readiness and only read from them if they have something to offer. The downside I could see here is that error isn’t ready, but eventually will be.

 3. 另外一个需要注意的地方是:

     如果调用的脚本中存在像sudo这样的需要tty的命令时,使用

           String []cmdArray = new String[]{ "/bin/sh", "-c", "yourscriptname"};

 这样的调用方式,会为脚本执行创建出一个tty环境,否则,运行过程会提示"sorry, you must have a tty to run xxx"的错误。

 

 

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

在exec()后 立即调用waitFor()会导致进程挂起。

 

 

 

 

相关文章:

1. When Runtime.exec() won't 关于Runtime的注意事项

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

2. java获取系统MAC地址

http://www.javapipe.com/web/memory_and_the_java_runtime.exec_process.html

3.  http://pudding.sharera.com/blog/BlogTopic/31232.htm


           
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: