使用stdin和stdout与Java通信外部C程序

时间:2011-03-13 02:42:21

标签: java c stdout stdin pipe

我要做的是在Java应用程序中启动C程序可执行文件,并允许它们使用stdin和stdout相互通信。 C程序将等待来自Java应用程序的命令并回显它。我用“gnugo --mode gtp”测试了java代码(gnugo在gtp模式下与stdin和stdout通信)并且它工作正常,但我的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代码

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)
        {

        }
    }
}

}

1 个答案:

答案 0 :(得分:6)

在退出之前尝试刷新标准输出,这可能会做得更好。或至少更详细地解释发生了什么。