Process 子类的一个实例,该实例可用来控制进程并获得相关信息。Process 类提供了执行从进程输入、执行输出到进程、等待进程完成、检查进程的退出状态以及销毁(杀掉)进程的方法。 创建进程的方法可能无法针对某些本机平台上的特定进程很好地工作,比如,本机窗口进程,守护进程,Microsoft Windows 上的 Win16/DOS 进程,或者 shell 脚本。
创建的子进程没有自己的终端或控制台。
它的所有标准 io(即 stdin、stdout 和 stderr)操作都将通过三个流 (getOutputStream()、getInputStream() 和 getErrorStream()) 重定向到父进程。
子线程的输入是主线程提供的,这个数据对主线程来说就是输出,即jvm线程的OutputStream数据是子线程的stdin;主线程的InputStream是子线程的stdout
父进程使用这些流来提供到子进程的输入和获得从子进程的输出。因为有些本机平台仅针对标准输入和输出流提供有限的缓冲区大小,如果读写子进程的输出流或输入流迅速出现失败,则可能导致子进程阻塞,甚至产生死锁。 当没有 Process 对象的更多引用时,不是删掉子进程,而是继续异步执行子进程。 对于带有 Process 对象的 Java 进程,没有必要异步或并发执行由 Process 对象表示的进程。
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.
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);
一个能用的demo:
原则:就是让标准输出和错误输出都使用专门的线程处理,这样可以避免子线程阻塞而导致的错误。建议使用proc.waitFor()
调用的地方:
public boolean execCommand(String commnad) {
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
OutputProcessor error = new OutputProcessor(proc.getErrorStream());
OutputProcessor input = new OutputProcessor(proc.getInputStream());
error.start();
input.start();
int exitCode = proc.waitFor();
if (exitCode == 0) {
return true;
}
return false;
} catch (Exception e) {
LOGGER.info("{}", e.getMessage(), e);
return false;
}
}
处理标准输出和错误输出的线程,因为就是防止子线程阻塞,没简单的输出没有特殊处理:
class OutputProcessor extends Thread {
private static final Logger LOGGER = LoggerFactory.getLogger(OutputProcessor.class);
private InputStream inputStream; public OutputProcessor(InputStream inputStream) {
this.inputStream = inputStream;
} @Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
LOGGER.info("{}", line);
}
} catch (Exception e) {
LOGGER.error("", e.getMessage(), e);
}
}
}
1.Stumbling into an IllegalThreadStateException
The first pitfall relating to Runtime.exec() is the IllegalThreadStateException.
import java.util.*;
import java.io.*;
public class BadExecJavac
{
public static void main(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("javac");
int exitVal = proc.exitValue();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t){t.printStackTrace();}
}
}
If an external process has not yet completed, the exitValue() method will throw an IllegalThreadStateException; that's why this program failed. While the documentation states this fact, why can't this method wait until it can give a valid answer?
A more thorough look at the methods available in the Process class reveals a waitFor() method that does precisely that. In fact, waitFor() also returns the exit value, which means that you would not use exitValue() and waitFor() in conjunction with each other, but rather would choose one or the other.
The only possible time you would use exitValue() instead of waitFor() would be
when you don't want your program to block waiting on an external process that may never complete.
import java.util.*;
import java.io.*; public class BadExecJavac2
{
public static void main(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("javac");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t){t.printStackTrace();}
}
}
Unfortunately, a run of BadExecJavac2 produces no output. The program hangs and never completes.
Why does the javac process never complete?
Why Runtime.exec() hangs
The JDK's Javadoc documentation provides the answer to this question:
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.
本地平台为标准的输入输出流只能提供有限的buffer,因此就不能够立即写子进程的输入流或者是读取子进程的输出流,这就会导致子进程的阻塞甚至死锁
import java.util.*;
import java.io.*;
public class MediocreExecJavac
{
public static void main(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("javac");
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</ERROR>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t){t.printStackTrace();}
}
}
So, MediocreExecJavac works and produces an exit value of 2. Normally, an exit value of 0 indicates success; any nonzero value indicates an error. The meaning of these exit values depends on the particular operating system.
Thus, to circumvent the second pitfall
-- hanging forever in Runtime.exec() --
if the program you launch produces output or expects input, ensure that you process the input and output streams.
3.Assuming a command is an executable program
import java.util.*;
import java.io.*; public class BadExecWinDir
{
public static void main(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("dir");//must run as rt.exec("cmd /C dir");
InputStream stdin = proc.getInputStream();//输入或输出是以jvm为参照物的,命令执行结果会输出到Jvm,对jvm来说命令的输出就是jvm的输入
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.println("<OUTPUT>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</OUTPUT>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
java BadExecWinDir
java.io.IOException: CreateProcess: dir error=2
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Unknown Source)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at BadExecWinDir.main(BadExecWinDir.java:12)
That's because the directory command is part of the Windows command interpreter and not a separate executable.
To run the Windows command interpreter, execute either command.com or cmd.exe, depending on the Windows operating system you use.
import java.util.*;
import java.io.*; class StreamGobbler extends Thread
{
InputStream is;
String type; StreamGobbler(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(type + ">" + line);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
} public class GoodWindowsExec
{
public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("USAGE: java GoodWindowsExec <cmd>");
System.exit(1);
} try
{
String osName = System.getProperty("os.name" );
String[] cmd = new String[3]; if( osName.equals( "Windows NT" ) )
{
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
else if( osName.equals( "Windows 95" ) )
{
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
} Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
Process proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(), "ERROR"); // any output?
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(), "OUTPUT"); // kick them off
errorGobbler.start();
outputGobbler.start(); // any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
java GoodWindowsExec "dir *.java"
Running GoodWindowsExec with any associated document type will launch the application associated with that document type.
For example, to launch Microsoft Word to display a Word document (i.e., one with a .doc extension), type:
>java GoodWindowsExec "yourdoc.doc"
Thus, to avoid the third pitfall related to Runtime.exec(), do not assume that a command is an executable program; know whether you are executing a standalone executable or an interpreted command.
It is important to note that the method used to obtain a process's output stream is called getInputStream(). The thing to remember is that the API sees things from the perspective of the Java program and not the external process. Therefore, the external program's output is the Java program's input. And that logic carries over to the external program's input stream, which is an output stream to the Java program.
4.Runtime.exec() is not a command line One final pitfall to cover with Runtime.exec() is mistakenly assuming that exec() accepts any String that your command line (or shell) accepts. Runtime.exec() is much more limited and not cross-platform.
import java.util.*;
import java.io.*; // StreamGobbler omitted for brevity public class BadWinRedirect
{
public static void main(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("java jecho 'Hello World' > test.txt");
// any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(), "ERROR"); // any output?
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(), "OUTPUT"); // kick them off
errorGobbler.start();
outputGobbler.start(); // any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
java BadWinRedirect
OUTPUT>'Hello World' > test.txt
ExitValue: 0
The program BadWinRedirect attempted to redirect the output of an echo program's simple Java version into the file test.txt. However, we find that the file test.txt does not exist. The jecho program simply takes its command-line arguments and writes them to the standard output stream.
Instead, exec() executes a single executable (a program or script). If you want to process the stream to either redirect it or pipe it into another program, you must do so programmatically, using the java.io package.
import java.util.*;
import java.io.*; class StreamGobbler extends Thread
{
InputStream is;
String type;
OutputStream os; StreamGobbler(InputStream is, String type)
{
this(is, type, null);
} StreamGobbler(InputStream is, String type, OutputStream redirect)
{
this.is = is;
this.type = type;
this.os = redirect;
} public void run()
{
try
{
PrintWriter pw = null;
if (os != null)
pw = new PrintWriter(os); InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
{
if (pw != null)
pw.println(line);
System.out.println(type + ">" + line);
}
if (pw != null)
pw.flush();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
} public class GoodWinRedirect
{
public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("USAGE java GoodWinRedirect <outputfile>");
System.exit(1);
} try
{
FileOutputStream fos = new FileOutputStream(args[0]);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("java jecho 'Hello World'");
// any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(), "ERROR"); // any output?
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(), "OUTPUT", fos); // kick them off
errorGobbler.start();
outputGobbler.start(); // any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
fos.flush();
fos.close();
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
java GoodWinRedirect test.txt
The solution to the pitfall was to simply control the redirection by handling the external process's standard output stream separately from the Runtime.exec() method.
before finalizing arguments to Runtime.exec() and writing the code, quickly test the arguments. Listing 4.8 is a simple command-line utility that allows you to do just that.
import java.util.*;
import java.io.*; // class StreamGobbler omitted for brevity public class TestExec
{
public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("USAGE: java TestExec \"cmd\"");
System.exit(1);
} try
{
String cmd = args[0];
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd); // any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(), "ERR"); // any output?
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(), "OUT"); // kick them off
errorGobbler.start();
outputGobbler.start(); // any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
java TestExec "explorer.exe aa.html"
To sum up, follow these rules of thumb to avoid the pitfalls in Runtime.exec():
1. You cannot obtain an exit status from an external process until it has exited
2. You must immediately handle the input, output, and error streams from your spawned external process
3. You must use Runtime.exec() to execute programs
4. You cannot use Runtime.exec() like a command line
http://web4.blog.163.com/blog/static/1896941312009124102715446/
http://tech.it168.com/j/2006-04-29/200604291539038.shtml
Runtime.exec() 不等同于直接执行command line命令!
Runtime.exec()很有局限性,对有些命令不能直接把command line里的内容当作String参数传给exec().
比如重定向等命令。举个例子:
javap -l xxx > output.txt
这时要用到exec的第二种重载,即input 参数为String[]:
Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","javap -l xxx > output.txt"});
rm -rf name*
Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","rm -rf name*"});
http://www.cnblogs.com/rspb/p/4648917.html
Runtime 封装着java程序的运行时环境。通过Runtime实例,java应用能够与其运行的环境连接。Runtime在jvm中保持一个单例,所以不能通过Runtime类的构造函数。只能通过Runtime.getRuntime()来获的当前Runtime的一个实例。获得Runtime实例后,就可以通过Runtime的exec()方法在当前jvm进程外启动其他进程了。很常见的一个应用就是,启动浏览器进程来显示一个程序的帮助页面。
在Runtime类中存在四个exec()重载方法.
- public Process exec(String command);
- public Process exec(String [] cmdArray);
- public Process exec(String command, String [] envp);
- public Process exec(String [] cmdArray, String [] envp);
主要参数是要启动进程的名称,以及启动该进程时需要的参数。然后是一些环境相关的属性。envp是已name=value,
形式传入的。具体查看下源码便一目了然了。
通常,启动另外一个进程后,需要获取另外一个进程的执行结果,然后根据结果执行后续的流程。要获取外部进程的运行结果,可以调用Process的exitValue() 方法。下面代码中启动一个java编译器进程。
- try {
- Runtime rt = Runtime.getRuntime();
- Process proc = rt.exec("javac");
- int exitVal = proc.exitValue();
- System.out.println("Process exitValue: " + exitVal);
- } catch (Throwable t) {
- t.printStackTrace();
- }
不幸的是,你将看到下面的结果:
java.lang.IllegalThreadStateException: process has not exited
at java.lang.ProcessImpl.exitValue(Native Method)
at com.test.runtime.Test.BadExecJavac(Test.java:13)
at com.test.runtime.Test.main(Test.java:5)
原因是exitValue()方法并不会等待外部进程结束。如果外部进程还未结束,exitValue()将会抛出IllegalThreadStateException。解决办法就是调用Process的waitfor()方法。waitfor()方法会挂起当前线程,一直等到外部进程结束。当然使用exitValue()或者waitfor()完全取决你的需求。可以设个boolean标志,来确定使用哪个。运行下面的代码:
- try {
- Runtime rt = Runtime.getRuntime();
- Process proc = rt.exec("javac");
- int exitVal = proc.waitFor();
- System.out.println("Process exitValue: " + exitVal);
- } catch (Throwable t) {
- t.printStackTrace();
- }
发现程序被阻塞了,什么原因呢?JDK's Javadoc文档解释说:
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.
翻译:
一些平台只为标准输入输出提供有限的缓存。错误的写子进程的输入流或者错误的都子进程的输出流都有可能造成子进程的阻塞,甚至是死锁。
解决上面问题的办法就是程序中将子进程的输出流和错误流都输出到标准输出中。
- try {
- Runtime rt = Runtime.getRuntime();
- Process proc = rt.exec("javac");
- InputStream stderr = proc.getErrorStream();
- InputStreamReader isr = new InputStreamReader(stderr);
- BufferedReader br = new BufferedReader(isr);
- String line = null;
- System.out.println("<ERROR>");
- while ((line = br.readLine()) != null)
- System.out.println(line);
- System.out.println("</ERROR>");
- int exitVal = proc.waitFor();
- System.out.println("Process exitValue: " + exitVal);
- } catch (Throwable t) {
- t.printStackTrace();
- }
上面的代码中仅仅是输出了错误流,并没有输出子进程的输出流。在程序中最好是能将子进程的错误流和输出流都能输出并清空。
在windows系统中,很多人会利用Runtime.exec()来调用不可执行的命令。例如dir和copy;
- try {
- Runtime rt = Runtime.getRuntime();
- Process proc = rt.exec("dir");
- InputStream stdin = proc.getInputStream();
- InputStreamReader isr = new InputStreamReader(stdin);
- BufferedReader br = new BufferedReader(isr);
- String line = null;
- System.out.println("<OUTPUT>");
- while ((line = br.readLine()) != null)
- System.out.println(line);
- System.out.println("</OUTPUT>");
- int exitVal = proc.waitFor();
- System.out.println("Process exitValue: " + exitVal);
- } catch (Throwable t) {
- t.printStackTrace();
- }
运行上面的代码,将会得到一个错误代码为2的错误。在win32系统中,error=2表示文件未找到。也就是不存在dir.exe和copy.exe。这是因为dir命令式windows中命令行解析器的一部分,并不是单独的一个可执行的命令。要运行上面的命令,得先启动windows下的命令行解析器command.com或者cmd.exe,这个取决于windows的系统的版本。
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- class StreamGobbler extends Thread {
- InputStream is;
- String type;
- StreamGobbler(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(type + ">" + line);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- }
- public class GoodWindowsExec {
- public static void main(String args[]) {
- if (args.length < 1) {
- System.out.println("USAGE: java GoodWindowsExec <cmd>");
- System.exit(1);
- }
- try {
- String osName = System.getProperty("os.name");
- String[] cmd = new String[3];
- if (osName.equals("Windows NT")) {
- cmd[0] = "cmd.exe";
- cmd[1] = "/C";
- cmd[2] = args[0];
- } else if (osName.equals("Windows 95")) {
- cmd[0] = "command.com";
- cmd[1] = "/C";
- cmd[2] = args[0];
- }
- Runtime rt = Runtime.getRuntime();
- System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
- Process proc = rt.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 (Throwable t) {
- t.printStackTrace();
- }
- }
- }
另外,Runtime.exec()并不是命令解析器,这是启动某个进程。并不能执行一些命令行的命令。下面是一个常见的错误:
- try {
- Runtime rt = Runtime.getRuntime();
- Process proc = rt.exec("java jecho 'Hello World' > test.txt");
- 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 (Throwable t) {
- t.printStackTrace();
- }
上面的代码希望像DOS系统中一样将命令的执行结果输出到文件中去。但是Runtime.exec()并不是命令行解析器。要想重定向输出流,必须在程序中编码实现。
- import java.util.*;
- import java.io.*;
- class StreamGobbler extends Thread {
- InputStream is;
- String type;
- OutputStream os;
- StreamGobbler(InputStream is, String type) {
- this(is, type, null);
- }
- StreamGobbler(InputStream is, String type, OutputStream redirect) {
- this.is = is;
- this.type = type;
- this.os = redirect;
- }
- public void run() {
- try {
- PrintWriter pw = null;
- if (os != null)
- pw = new PrintWriter(os);
- InputStreamReader isr = new InputStreamReader(is);
- BufferedReader br = new BufferedReader(isr);
- String line = null;
- while ((line = br.readLine()) != null) {
- if (pw != null)
- pw.println(line);
- System.out.println(type + ">" + line);
- }
- if (pw != null)
- pw.flush();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- }
- public class GoodWinRedirect {
- public static void main(String args[]) {
- if (args.length < 1) {
- System.out.println("USAGE java GoodWinRedirect <outputfile>");
- System.exit(1);
- }
- try {
- FileOutputStream fos = new FileOutputStream(args[0]);
- Runtime rt = Runtime.getRuntime();
- Process proc = rt.exec("java jecho 'Hello World'");
- StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
- StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", fos);
- errorGobbler.start();
- outputGobbler.start();
- int exitVal = proc.waitFor();
- System.out.println("ExitValue: " + exitVal);
- fos.flush();
- fos.close();
- } catch (Throwable t) {
- t.printStackTrace();
- }
- }
- }
http://www.cnblogs.com/nkxyf/archive/2012/12/13/2815978.html