【发布时间】:2018-05-18 06:22:28
【问题描述】:
我正在使用java(虽然有很多可用的,但我想要自己的)开发一种用于 C/C++ 的 IDE 软件,它可以编译和执行 C 或 C++ 程序。所以我尝试了一个简单的程序来使用Process和ProcessBuilder.在java中编译和执行C程序
这是我编译和执行 C 程序的简单 java 程序:
public class RunProgram {
public static void main(String[] args) throws Exception {
new ProcessBuilder("gcc", "-o", "first", "first.c").start().waitFor(); //To Compile the source file using gcc and wait for compilation
/*
Although I've to handle error-stream but
for now, my assumption is that there is no error
in program.
*/
ProcessBuilder run = new ProcessBuilder("./first");
execute.redirectErrorStream(true);
Process runProcess = run.start();
StreamReader sr = new StreamReader(runProcess.getInputStream());
new Thread(sr).start(); //A new thread to handle output of program .
//rest of coding to provide input using OutputStream of 'runProcess' and to close the stream.
}
}
class StreamReader implements Runnable {
private InputStream reader;
public StreamReader(InputStream inStream) {
reader = inStream;
}
@Override
public void run() {
byte[] buf = new byte[1024];
int size = 0;
try {
while ((size = reader.read(buf)) != -1) {
System.out.println(new String(buf));
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是我的first.c 程序。
#include<stdio.h>
int main() {
int a;
int k;
printf("input a: ");
scanf("%d", &a);
for(k = 0; k < a; k++)
printf("k = %d\n", k);
return 0;
}
我想创建交互式IO 控制台,就像大多数 IDE 或命令终端(基于 Linux 的操作系统中的终端和基于 Windows 的操作系统中的命令提示符)。对于上面的例子:首先,它应该打印“Input a: “然后等待输入被提供,然后是程序的其余部分。但它不会像我想的那样工作,因为它没有' t 打印出现在scanf 之前的printf 语句的结果,直到我可能使用OutputStream 提供输入。
我搜索了我的问题并访问了许多链接,但没有得到解决方案。同时,我发现this 链接建议在每个printf 语句之后附加fflush 或使用setbuf 或setvbuf 方法(来自其他一些子链接)来清除缓冲区。但是一个新人(即将学习 C)可能不知道fflush 或这些功能,他/她永远不会使用它,因为它在其他 IDE 中不需要,甚至在终端上也不需要。
如何解决这个问题并为我的 IDE 构建集成控制台
这是我想要的一瞥:
【问题讨论】:
-
我的这个answer 更深入地解释了幕后发生的事情以及为什么应该在被调用程序中处理它。我能想象的唯一选择是 Unix-Linux 中的伪终端,但它是一种相当先进(且不可移植)的方式。
-
@SergeBallesta 我看过你的回答,但我不明白你的回答将如何帮助我解决这个问题。
-
不幸的是,没有办法解决它(除了伪终端)......
-
@SergeBallesta eclipse 和其他 IDE 也使用伪终端
标签: java process io processbuilder