Runtime exec如何在不使用waitfor()的情况下确定进程何时终止?
Runtime exec how to determine when the process terminates without using waitfor()?
我正在 运行 宁一个 shell 命令需要相当长的时间来执行,命令 运行 没有问题,但我无法让进程中止一次开始了。我正在使用 AsyncTask class 到 运行 命令来避免阻塞主线程,代码如下:
private class Worker extends AsyncTask <String, Integer, Integer>
{
@Override
protected Integer doInBackground (String... args)
{
Process proc = runtime.getRuntime.exec ("some long process...");
while (/*process still running*/)
{
if (isCancellled()) proc.destroy();
}
return proc.exitValue();
}
.....
}
Worker w = new Worker();
w.execute();
w.cancel (true); // abort
如何在不阻塞 AsyncTask 线程的情况下确定进程何时完成?我如何捕获 AsyncTask 取消信号并中止进程?
我找到了一个在启动后中止运行时进程的简单解决方案,我只是在 AsyncTask class 中添加了对该进程的引用,当我需要中止 shell 命令时,我会在进程上调用 destroy
方法,它将终止:
private class Worker extends AsyncTask <String, Integer, Integer>
{
private Process proc;
@Override
protected Integer doInBackground (String... args)
{
try
{
this.proc = Runtime.getRuntime().exec (command);
this.proc.waitFor();
InputStream out = this.proc.getInputStream();
out.skip (out.available());
InputStream err = this.proc.getErrorStream();
err.skip (err.available());
}
catch (InterruptedException ex)
{
Log.i ("runCommand", "Interruped Exception");
ex.printStackTrace();
return -1;
}
catch (IOException ex)
{
ex.printStackTrace();
return -1;
}
return proc.exitValue();
}
public void abort()
{
if (this.proc != null) this.proc.destroy();
}
}
Worker w = new Worker();
w.execute();
w.abort(); // Terminates the process
我正在 运行 宁一个 shell 命令需要相当长的时间来执行,命令 运行 没有问题,但我无法让进程中止一次开始了。我正在使用 AsyncTask class 到 运行 命令来避免阻塞主线程,代码如下:
private class Worker extends AsyncTask <String, Integer, Integer>
{
@Override
protected Integer doInBackground (String... args)
{
Process proc = runtime.getRuntime.exec ("some long process...");
while (/*process still running*/)
{
if (isCancellled()) proc.destroy();
}
return proc.exitValue();
}
.....
}
Worker w = new Worker();
w.execute();
w.cancel (true); // abort
如何在不阻塞 AsyncTask 线程的情况下确定进程何时完成?我如何捕获 AsyncTask 取消信号并中止进程?
我找到了一个在启动后中止运行时进程的简单解决方案,我只是在 AsyncTask class 中添加了对该进程的引用,当我需要中止 shell 命令时,我会在进程上调用 destroy
方法,它将终止:
private class Worker extends AsyncTask <String, Integer, Integer>
{
private Process proc;
@Override
protected Integer doInBackground (String... args)
{
try
{
this.proc = Runtime.getRuntime().exec (command);
this.proc.waitFor();
InputStream out = this.proc.getInputStream();
out.skip (out.available());
InputStream err = this.proc.getErrorStream();
err.skip (err.available());
}
catch (InterruptedException ex)
{
Log.i ("runCommand", "Interruped Exception");
ex.printStackTrace();
return -1;
}
catch (IOException ex)
{
ex.printStackTrace();
return -1;
}
return proc.exitValue();
}
public void abort()
{
if (this.proc != null) this.proc.destroy();
}
}
Worker w = new Worker();
w.execute();
w.abort(); // Terminates the process