使用标准输入和stdout与Java外部C程序进行通信
我试图做的是启动C程序可执行Java应用程序里面,让他们互相使用stdin和stdout沟通。 C程序将等待来自Java应用程序的命令和回声回来。我测试了Java code。与gnugo --mode GTP(gnugo在GTP模式stdin和stdout通讯),它工作正常,但我不能与我的C code工作。任何建议将大大AP preciated。
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 $ C $ç
#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
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)
{
}
}
}
}
你试试退出前潮红标准输出,这可能做的更好。或者更详细地是什么发生,至少说明。
Try flushing stdout before you exit, that might do better. Or at least explain in more detail what does happen.