我写了以下代码。为了从Java应用程序运行bat文件,我使用process.exec()。但是,bat有时可能会挂起,因此我需要为此进程设置超时。我在新线程中启动一个新进程,设置线程超时,并在超时时杀死线程。但是,当超时发生时,我发现进程无法被销毁。所以我对如何杀死进程感到困惑?
代码:
StreamGobbler:
代码:
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();
}
}
}
主要:
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();
}
}
}
rt.exec("skynet")
可能会忽略Process.destroy()
调用。 - corsiKa