本文旨在解决Java程序中创建并维持一个长期运行的命令行进程的问题。通过分析现有代码中进程意外终止的原因,并提供修改后的代码示例,演示了如何正确地与子进程进行输入输出交互,从而确保子进程在整个Java应用程序生命周期内保持运行。本文提供了避免资源泄露和死锁的关键实践,并探讨了使用后台线程处理输入输出流的替代方案。
在Java程序中创建并维持一个长期运行的命令行进程,需要特别注意进程的输入输出流管理。如果处理不当,子进程可能会意外终止,或者导致程序死锁。以下是如何解决这个问题的详细步骤和示例代码。
问题分析
原始代码中,子进程在第一次迭代后终止,这是因为PrintWriter stdin 被放置在 while 循环内的 try-with-resources 块中。这意味着每次循环迭代结束时,stdin 都会被关闭,从而关闭了子进程的标准输入流。当子进程的标准输入流关闭时,cmd.exe 也会随之终止。
立即学习“Java免费学习笔记(深入)”;
解决方案
要解决这个问题,需要确保子进程的标准输入流在整个Java应用程序的生命周期内保持打开状态。以下是一些可行的解决方案:
将 PrintWriter 移到循环外部
将 PrintWriter 的声明和初始化移到 while 循环外部,以确保它在整个循环过程中保持打开状态。
class CommandLine { Process Handle; Scanner getCommand; Socket socket; PrintWriter stdin; // 声明 PrintWriter 在循环外部 public CommandLine(Socket socket) throws IOException { this.socket = socket; } public void executeCommand() { try { getCommand = new Scanner(socket.getInputStream()).useDelimiter("\A"); Handle = new ProcessBuilder("cmd.exe").redirectErrorStream(true).start(); stdin = new PrintWriter(Handle.getOutputStream()); // 初始化 PrintWriter 在循环外部 while (getCommand.hasNextLine()) { try { stdin.write(getCommand.nextLine() + System.lineSeparator()); stdin.flush(); } catch (Exception e) { e.printStackTrace(); // 处理写入错误 break; // 退出循环,避免无限重试 } if (Handle.getInputStream().available() > 0) { // 使用 available() 检查是否有数据可读 Scanner result = new Scanner(Handle.getInputStream()).useDelimiter("\A"); while (result.hasNextLine()) { System.out.print(result.nextLine() + " "); } } } } catch (IOException e) { e.printStackTrace(); } finally { // 确保资源被正确关闭 if (stdin != null) { stdin.close(); } if (Handle != null) { Handle.destroy(); // 确保进程被销毁 } } } }
注意事项:
使用 inheritIO() 或 redirectOutput(ProcessBuilder.Redirect.INHERIT)
使用 ProcessBuilder.inheritIO() 或 ProcessBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT) 可以将子进程的标准输入、输出和错误流重定向到 Java 进程。这样就不需要手动读取和写入流。
class CommandLine { Process Handle; Scanner getCommand; Socket socket; public CommandLine(Socket socket) throws IOException { this.socket = socket; } public void executeCommand() { try { getCommand = new Scanner(socket.getInputStream()).useDelimiter("\A"); Handle = new ProcessBuilder("cmd.exe").inheritIO().start(); // 使用 inheritIO() //Handle = new ProcessBuilder("cmd.exe").redirectOutput(ProcessBuilder.Redirect.INHERIT).redirectError(ProcessBuilder.Redirect.INHERIT).start(); // 或者使用 redirectOutput 和 redirectError try (PrintWriter stdin = new PrintWriter(Handle.getOutputStream())) { while (getCommand.hasNextLine()) { stdin.write(getCommand.nextLine() + System.lineSeparator()); stdin.flush(); } } } catch (IOException e) { e.printStackTrace(); } finally { if (Handle != null) { Handle.destroy(); } } } }
注意事项:
使用后台线程处理输入输出流
为了避免阻塞主线程,可以使用后台线程来处理子进程的输入和输出流。
import java.io.*; import java.net.Socket; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class CommandLine { Process Handle; Scanner getCommand; Socket socket; private final ExecutorService executor = Executors.newFixedThreadPool(2); // 创建线程池 public CommandLine(Socket socket) throws IOException { this.socket = socket; } public void executeCommand() { try { getCommand = new Scanner(socket.getInputStream()).useDelimiter("\A"); Handle = new ProcessBuilder("cmd.exe").redirectErrorStream(true).start(); // 启动线程读取子进程的输出 executor.submit(() -> { try (Scanner result = new Scanner(Handle.getInputStream()).useDelimiter("\A")) { while (result.hasNextLine()) { System.out.println(result.nextLine()); } } catch (Exception e) { e.printStackTrace(); } }); // 主线程负责写入子进程的输入 try (PrintWriter stdin = new PrintWriter(Handle.getOutputStream())) { while (getCommand.hasNextLine()) { stdin.write(getCommand.nextLine() + System.lineSeparator()); stdin.flush(); } } Handle.waitFor(); // 等待子进程完成 } catch (IOException | InterruptedException e) { e.printStackTrace(); } finally { executor.shutdown(); // 关闭线程池 if (Handle != null) { Handle.destroy(); } } } }
注意事项:
总结
在Java中创建永久存活的进程,关键在于正确管理子进程的输入输出流。避免在循环内部关闭输入流,使用 inheritIO() 或后台线程处理输入输出流,可以确保子进程在整个Java应用程序的生命周期内保持运行。同时,要记得在程序结束时关闭流和销毁进程,以避免资源泄露。
以上就是Java中创建永久存活的进程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号