【发布时间】:2015-04-13 22:15:27
【问题描述】:
我正在尝试使用进程构建器通过 Java 调用 C 程序。通过 Java,我将编译 C 程序(它会编译)然后运行它,它不会。
我希望终端显示 Result: 6 但没有显示
Java 程序(main.java)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class main
{
public static void main(String[] args) throws InterruptedException, IOException
{
//compile + run
Process compile = new ProcessBuilder("gcc", "calculator.c").start();
//delay program to allow ./a.out to create
try
{
Thread.sleep(1000); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
Process execute = new ProcessBuilder("./a.out").start();
}
}
C 程序:(calculator.c)
#include <stdio.h>
int main ()
{
int a = 4;
int b = 2;
int c = a + b;
printf("Result: %d \n", c);
}
【问题讨论】:
-
您需要阅读进程的
Input/ErrorStream以查看它输出的内容,例如this -
感谢您的回复,试过了,看起来很费解!我需要添加一个全新的方法吗?
-
你只需要使用
Input/ErrorStream,我倾向于使用Thread,因为我喜欢调用Process#waitFor,所以我可以获得Process的退出代码,但是因为这是一个阻塞调用,我也使用Thread来消耗流,但这只是我