我写了下面的代码.要从Java应用程序运行bat文件,我使用process.exec().但是蝙蝠可能会在某个时候挂起,所以我需要为这个过程设置一个超时.我在线程中启动一个新线程和一个新进程,我在线程中设置了一个超时,并在超时时终止该线程.但我发现超时发生时无法销毁进程.所以我很担心如何杀死这条庄园?
代码:
StreamGobbler:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
主要:
public class test
{
public static void main(String args[]) throws InterruptedException
{
Runnable r = new ShengThread();
Thread sheng = new Thread(r);
sheng.start();
sheng.join(1000);
if (sheng.isAlive()) {
sheng.interrupt();
}
if (sheng.isAlive()) {
System.out.println("It is dead.");
}
}
}
class ShengThread implements Runnable {
public void run() {
Process proc = null;
try
{
String osName = System.getProperty("os.name" );
String[] cmd = new String[3];
if( osName.equals( "Windows XP" ) )
{
cmd[0] = "cmd" ;
cmd[1] = "/C" ;
cmd[2] = "c:\\status.bat";
}
Runtime rt = Runtime.getRuntime();
System.out.println(osName+"Execing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
try {
proc = rt.exec(cmd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 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 (InterruptedException t)
{
System.out.println("start\n");
proc.destroy();
t.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
该Process.destroy()
方法强制销毁外部进程......如果可行的话.(在某些情况下,你不能破坏进程,但这只是勉强相关.)
归档时间: |
|
查看次数: |
5487 次 |
最近记录: |