通过Java与C ++进程进行通信
首先,我在网站上看到有关此问题的一些问题,但没有找到解决我问题的答案.
First, I saw a few Q's about this issue in the site, but didn't see any answer that solve my problem.
我有一个用Java编写的程序,它调用了一个用C ++编写的cmd程序. (这是一个假设,因为我没有实际的来源)我知道C ++程序的预期I/O,在cmd中它是两行输出,然后等待字符串输入. 我知道程序的第一行输出是通过错误流,并且我正确地接收了它(这是预期的),但是我没有得到错误或输入流的第二行. 我试图在第一行(错误行)之后立即写入程序,但没有卡住,但是没有响应. 我尝试为每个流使用3个不同的线程,但同样,在第一行之后输入/错误流中什么也没收到,并且程序对通过输出流进行写入没有响应.
I have a program written in Java and it calls a cmd program written in C++. (this is an assumption since I don't have the actual source) I know the expected I/O of the C++ program, in the cmd it is two lines of output and then it waits for string input. I know that the first output line of the program is through error stream, and I receive it properly (this is expected), but I don't get the second line in error or input stream. I tried to write to the program right after the first line ( the error line) and didn't got stuck, but there was no response. I tried using 3 different threads, for each stream, but again, nothing was received in input/error stream after the first line, and the program didn't respond to writing through output stream.
我的初始值设定项是:
Process p = Runtime.getRuntime().exec("c:\\my_prog.exe");
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
是否完全有可能,或者取决于C ++程序?
Is it possible at all or maybe it depends on the C++ program?
谢谢, Binyamin
Thanks, Binyamin
这是我在Java中执行任何命令行的方式.此命令行可以执行任何程序:
Here is how I execute any command line in Java. This command line may execute any program:
private String executionCommandLine(final String cmd) {
StringBuilder returnContent = new StringBuilder();
Process pr;
try {
Runtime rt = Runtime.getRuntime();
pr = rt.exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
returnContent.append(line);
}
input.close();
LOG.debug(returnContent.toString());
// return the exit code
pr.waitFor();
} catch (IOException e) {
LOG.error(e.getMessage());
returnContent = new StringBuilder();
} catch (InterruptedException e) {
LOG.error(e.getMessage());
returnContent = new StringBuilder();
}
return returnContent.toString();
}