Reputation: 2792
In the following scenario we're dealing with a console application where there is a PHP script running as a process from within a java application. Each time the script is fed with two values and returns either "OK" or "ERR". I'm trying to capture the time it takes from when the inputs are fed into the script and the time it return with either an "OK" or "ERR" value.
I have implemented the following fix, but it still doesn't seem to work. If anyone could shed some light.
try {
proc = runtime.exec("php " + "script.php");
inp = new BufferedReader( new InputStreamReader(proc.getInputStream()) );
out = new BufferedWriter( new OutputStreamWriter(proc.getOutputStream()) );
while (true) {
temp = getRandomUser() + " " + getRandomHost();
startTime = System.currentTimeMillis();
//System.out.println(temp);
print(pipe(temp));
while (!inp.readLine().equals("ERR") || !inp.readLine().equals("OK")) {
}
endTime = System.currentTimeMillis();
procTime = (long) endTime - startTime;
fout.write(Double.toString(procTime));
fout.newLine();
//System.out.println("! " + procTime);
}
} catch (IOException ex) {
System.out.println("Thread prematurely Terminated...");
}
Upvotes: 0
Views: 81
Reputation: 719679
Your description of the symptoms is unclear. However, this like is almost certainly wrong:
while (!inp.readLine().equals("ERR") || !inp.readLine().equals("OK")) {
}
Firstly, if you reach the end of stream, readLine will return null
, and you will get an NPE when you try to invoke equals
on it.
Second, the condition is actually calling readLine()
twice. It looks like you intent is to read and throw away lines until you get one that matches "ERR" or "OK". But the code doesn't do that. Indeed, if the first significant line it reads is "OK", the condition won't fire ... and you will keep on trying to read. The code should be like this:
String line = inp.readLine();
while (line != null && !line.equals("ERR") && !line.equals("OK")) {
line = inp.readLine();
}
This bug is certainly sufficient to explain why the code would block ...
Upvotes: 1