我创建类来连续执行CMD命令--在下面的代码中,第一次迭代运行良好,但是问题是,在完成一次迭代之后,这个过程就死了。
class CommandLine{
Process Handle ;
OutputStreamWriter writer;
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").redirectErrorStream(true).start();
while(getCommand.hasNextLine()) {
try(PrintWriter stdin = new PrintWriter(Handle.getOutputStream())) {
stdin.write(getCommand.nextLine()+System.lineSeparator());
stdin.flush();
}
if(Handle.getInputStream().read()>0) {
Scanner result = new Scanner(Handle.getInputStream()).useDelimiter("\\A");
while(result.hasNextLine()) {
System.out.print(result.nextLine()+"\n");
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}thx响应
发布于 2022-10-28 12:57:23
你需要重新组织你的代码。子进程会死,因为循环中有一个带有资源块的尝试:
try(PrintWriter stdin = new PrintWriter(Handle.getOutputStream())) {
stdin.write(getCommand.nextLine()+System.lineSeparator());
stdin.flush();
}上面的意思是子进程的STDIN在一行之后结束,CMD.EXE也是如此。
还请注意,仅将PrintWriter stdin部件移出循环是不够的。您将无法可靠地提供STDIN并在同一个循环中读取STDOUT,因为STDOUT可能是多行输入,并在编写STDIN时阻塞进程。
修复方法很简单:遵循@VGR建议并将.redirectErrorStream(true)替换为.redirectOutput(ProcessBuilder.Redirect.INHERIT)或.inheritIO(),这意味着您不需要阅读getInputStream()。或者,在编写STDIN或从getInputStream() / STDOUT读取代码时,可以使用后台线程。
https://stackoverflow.com/questions/74235244
复制相似问题