I wait to start a process, pass an integer to it, and get a value which it prints out. I tried the following (in Windows):
public class Example {
public static Boolean call() throws IOException {
String mFilename = "f.exe";
int mParam = 0;
Process p = Runtime.getRuntime().exec(mFilename);
BufferedReader input = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedWriter output = new BufferedWriter
(new OutputStreamWriter(p.getOutputStream()));
output.write(mParam);
output.flush();
char retVal = (char) input.read();
return !(retVal == '0');
}
public static void main(String[] args) throws IOException {
System.out.println(call());
}
}
mFilename is a path to the executable. The process returns 1 for positive input, 0 for negative, and remains in an infinite loop if mParam is 0. However, I found out that no matter what value I pass to it, retVal is always 1. What am I doing wrong?
Excuse me for deleting the question a few minutes before, I thought the problem was in retVal but apparently it was not the only problem in this code.
Child process, written in C++:
#include <iostream>
#include <Windows.h>
bool f(int x)
{
if (x)
return x > 0;
while (1)
Sleep(100);
}
int main()
{
int x;
std::cin>>x;
std::cout<<f(x);
}
Update:
I found at least one of the errors. Since mParam is an integer, which consists of an optional sign and a bunch of digits, and output.write writes characters, I need to write my integer as a character array:
char[] arr = String.valueOf(mParam).toCharArray();
output.write(arr);
However, regardless of the input, after this fix program hangs at
char retVal = (char) input.read();
Well, the solution turned out to be quite simple:
std::cinjust wanted a newline to successfully read the integer. Resulting code is as follows:Note that I added support for the ‘infinite loop’-case scenario. If we are unable to get the output from stdout in 3 seconds, we throw exception and terminate the child process. I don’t process the exception here because the function has to return some result, but in the case of infinite loop I don’t have any result to return.