We are trying to create a java application that uses a C++ executable that performes an algorimth seperately. To have java and C++ communication we use cout and getline in C++ and while true loop with reader.readline in java. The problem arise when using cygwin as compiler for C++. As soon as java starts it receives null from c++ continuously. We are at a loss of what it problem is as the while loop had worked previously.
Java part
import java.io.*;
public class Main {
private static ProcessBuilder pb;
private static Process process;
private static BufferedReader reader;
private static BufferedWriter writer;
public static void main(String[] args) throws IOException{//TransformException
pb = new ProcessBuilder();
pb.command("C:/Users/*USERNAME*/CLionProjects/untitled/cmake-build-debug/untitled.exe"); // C++ executable
process = pb.start();
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
ReaderThread rd = new ReaderThread(reader);
rd.start();
while(true){
String input = inputReader.readLine();
String lineToSend;
switch(input.toLowerCase()){
case "run":
String arg1 = "first";
String arg2 = "second";
lineToSend = "runExample"+" " + arg1 + " "+ arg2 + "\n";
writer.write(lineToSend);
writer.flush();
break;
}
}
}
}
import java.io.IOException;
class ReaderThread extends Thread {
BufferedReader reader;
public ReaderThread(BufferedReader reader) {
this.reader = reader;
}
public void run() {
try {
String reply;
System.out.println("Reader thread ready");
while (true) {
reply = reader.readLine();
String[] replyAsArr = {"No reply"};
if (reply != null) {
replyAsArr = reply.split(" ");
} else System.out.println("Got reply: " + reply);
switch (replyAsArr[0]) {
case "result":
System.out.println("Got result");
break;
case "info":
System.out.println(reply);
break;
default:
System.out.println("Malformed input from cpp: " + reply);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
C++ part (CppPart.exe)
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <map>
using namespace std;
void runAlgorithm() {
cout << "result" << endl;
cout << flush;
}
void communicateWithJava() {
enum commands{
ERROR,
runExample,
};
map<string, commands> mapStringToEnum =
{
{"error", ERROR},
{"runExample", runExample},
};
string line;
while(getline(cin, line)) {
istringstream buf(line);
istream_iterator<string> beg(buf), end;
vector<string> lineAsTokens(beg, end);
commands switchType = mapStringToEnum[lineAsTokens[0]];
switch (switchType) {
case ERROR: {
cout << "Could not understand input: "<< line << endl;
cout << flush;
break;
}
case runExample: {
runAlgorithm();
cout << "info " << lineAsTokens[1] << lineAsTokens[2] << endl;
cout << flush;
break;
}
}
}
}
int main() {
communicateWithJava();
return 0;
}