我有一个需要使用ProcessBuilder启动进程的场景。成功启动流程后,打开创建流程的输入流和输出流,并通过输出流传递参数,并通过输入流检索结果。
它在第一次执行过程中工作正常。 但是如果我需要循环多次,并且将不同的参数传递给同一个创建的进程,则它会失败并且Process.isAlive()将返回false。
在我们的场景中,该过程只需要启动一次。 因此,请帮助我使流程保持活跃,并使用相同的流程来完成所有功能。
代码段
ProcessBuilder pb = new ProcessBuilder(command);
Process p = pb.start();
ServerSocket server = new ServerSocket(8765);
PrintWriter pw = new PrintWriter(p.getOutputStream());
BufferedReader br = new BufferedReader( new
InputStreamReader(p.getInputStream()) );
while(true){
System.out.println("The p value is "+p.isAlive());
//server waiting for client to connect
Socket sock = server.accept();
//reading the argument for the "command"
DataInputStream dis = new DataInputStream(sock.getInputStream());
String arg=(String)dis.readUTF();
System.out.println("data received is = "+arg);
//code for executing the process p(command) with the arguments received from socket
pw.println(arg);
pw.flush();
pw.close();
String line = "";
String result ="";
//storing the result of the final_cmd with arguments in the result string
while ((line = br.readLine()) != null) {
result=result+line+System.lineSeparator();
}
//result returning back to socket
DataOutputStream dout=new DataOutputStream(sock.getOutputStream());
dout.writeUTF(result);
dout.flush();
}