ProcessBuilder.start()
和 Runtime.exec
方法创建一个本机进程。并返回 Process
子类的一个实例,该实例可用来控制进程并获得相关信息。Process
类提供了执行从进程输入、执行输出到进程、等待进程完成、检查进程的退出状态以及销毁(杀掉)进程的方法。Runtime
that
allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime
method. getRuntime()方法来获取一个Runtime实例。
1.3执行一条shell命令
String commend=".....";//一条shell命令
Process pro=Runtime.getRuntime().exec(commend);
//exec方法会返回一个单独的进程用来管理子进程(
A
new Process
object
for managing the subprocess)。 pro.waitFor()
;//导致当前线程等待,如有必要,一直要等到由该
Process
对象表示的进程已经终止。(causes
the current thread to wait, if necessary, until the process represented by this Process
object has
terminated.)也可以意味着命令运行成功,没有发生堵塞。eg: 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);
1.4 .2. 永远要在调用waitFor()方法之前读取数据流
永远要先从标准错误流中读取,然后再读取标准输出流
1.4 .3. 另外一个需要注意的地方是:
如果调用的脚本中存在像sudo这样的需要tty的命令时,使用
String []cmdArray = new String[]{ "/bin/sh", "-c", "yourscriptname"};
这样的调用方式,会为脚本执行创建出一个tty环境,否则,运行过程会提示"sorry, you must have a tty to run xxx"的错误