期望输入时终止子进程

时间:2019-03-11 12:26:06

标签: java processbuilder

public static int launch(String pathTojar ,String params) throws IOException, InterruptedException {

    byte[] buffer = new byte[1024];      
    ProcessBuilder processBuilder = new ProcessBuilder("java", "-jar", pathTojar, "L", "C", params);
    processBuilder.redirectErrorStream(true);
    processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT);
    Process process = processBuilder.start();
    //kill child process when parent process dies
    Runtime.getRuntime().addShutdownHook(new Thread(process::destroyForcibly));
    InputStream in = process.getInputStream();

    Thread t = new Thread(() -> {
        while (true) {
            int r = 0;
            try {
                r = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (r <= 0) {
                break;
            }
            System.out.write(buffer, 0, r);
        }});
        t.start();

    return process.waitFor();
}

子进程仅在CTRL+C上退出(子进程询问用户“用户是否要继续下一个循环”),这将杀死父进程(当前线程)。如何在显示问题(即期望输入)时杀死子进程而不杀死其父进程。

先谢谢了。

0 个答案:

没有答案