I had a scenario where a process need to be started using ProcessBuilder. After starting the process successfully, I open the inputstream and outputstream of the created process and passed the arguments through the outputstream and retrieved the result through the inputstream.
It is working fine for the first time execution in the process. But if I need to loop multiple times with different arguments passed to the same created process, it is failing and the Process.isAlive() is returned as false.
In our scenario, the process need to be started only once. So please help me in making the process be alive and use the same process for the complete functionality.
Code snippet
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();
}