Java程序运行、停止Shell脚本

用Java程序来控制shell脚本的运行和停止。具体来讲,这个Java程序至少要有三个功能:

  1. 运行Shell脚本;
  2. 等待Shell脚本执行结束;
  3. 停止运行中的Shell程序;

从功能需求来看,似乎是比较容易做到的。尽管没有写过类似功能的程序,Google一下,很快就有答案了。

用Runtime或者ProcessBuilder可以运行程序,而Process类的waitFor()和destroy()方法分别满足功能2和3。

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;


public class ShellRunner extends Thread
{
  private Process proc;
  private String dir;
  private String shell;

  public ShellRunner(String dir, String shell)
  {
    super();
    this.proc = null;
    this.dir = dir;
    this.shell = shell;
  }

  @Override
  public void run() {
    try
    {
      ProcessBuilder builder = new ProcessBuilder("sh", dir + shell);
      builder.directory(new File(dir));

      proc = builder.start();
      System.out.println("Running ...");
      int exitValue = proc.waitFor();
      System.out.println("Exit Value: " + exitValue);
    }
    catch (IOException e)
    {
      e.getLocalizedMessage();
    }
    catch (InterruptedException e)
    {
      e.getLocalizedMessage();
    }
  }

  public void kill()
  {
    if (this.getState() != State.TERMINATED) {
      proc.destroy();
    }
  }

  public static void main(String args[]) {
    ShellRunner runner = new ShellRunner("/tmp/", "run.sh");
    runner.start();

    InputStreamReader inputStreamReader = new InputStreamReader(System.in);
    BufferedReader reader = new BufferedReader(inputStreamReader);
    try
    {
      String line = null;
      while ( (line = reader.readLine()) != null ) {
        if (line.equals("kill")) {
          runner.kill();
        }
        else if (line.equals("break")) {
          break;
        }
        else {
          System.out.println(runner.getState());
        }
      }
      reader.close();
      inputStreamReader.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }

  }
}
waitFor()方法可以正确等待shell程序退出,但是destroy()方法并没有结束shell脚本相关的进程。

这是一个BUG

JDK-bug-4770092:Process.destroy()不能结束孙子进程(grandchildren)。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值