What I'm trying to do is launch the C program executable inside the Java application and allow them to communicate with each other using stdin and stdout. The C program will wait for a command from the java app and echo it back. I've tested the java code with "gnugo --mode gtp" (gnugo with in gtp mode communicates with stdin and stdout) and it works fine but my doesn't work with my C code. Any suggestion would greatly appreciated.
C code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
unsigned int byte_read;
char *string, *tok;
int cmd_id;
int len = 64;
string = (char *) malloc(len + 1);
while (1) {
byte_read = getline(&string,&byte_read, stdin);
if (byte_read == -1) {
printf("Error reading input\n");
free(string);
exit(0);
//
} else {
printf("Got command: %s\n", string);
}
}
return EXIT_SUCCESS;
}
Java code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Test {
private BlockingQueue<String> m_queue;
private PrintWriter print_out;
private BufferedReader bufIn;
private InputThread inputThread;
private PrintWriter printOut;
private Process p;
public static void main(String[] args) {
Test test = new Test();
test.start();
}
public void start(){
try
{
Runtime rt = Runtime.getRuntime() ;
p = rt.exec("path/to/the/c/program") ;
InputStream in = p.getInputStream() ;
OutputStream out = p.getOutputStream ();
InputStream err = p.getErrorStream();
printOut = new PrintWriter(out);
m_queue = new ArrayBlockingQueue<String>(10);
inputThread = new InputThread(in, m_queue);
inputThread.start();
//send a command to
printOut.println("sample command");
printOut.flush();
//p.destroy() ;
}catch(Exception exc){
System.out.println("Err " + exc.getMessage());
}
}
private void mainLoop(){
String line;
while (true){
try
{
System.out.println("Before");
line = bufIn.readLine();
System.out.println("After");
if (line != null)
System.out.println(line);
}
catch (IOException e)
{
System.out.println("Error readline " + e.getMessage());
return;
}
}
}
private class InputThread extends Thread
{
InputThread(InputStream in, BlockingQueue<String> queue)
{
bufIn = new BufferedReader(new InputStreamReader(in));
m_queue = queue;
}
public void run()
{
try
{
mainLoop();
}
catch (Throwable t)
{
}
}
}
}