【问题标题】:java process builder with c not displaying results?带有c的java进程生成器不显示结果?
【发布时间】: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 来消耗流,但这只是我

标签: java c


【解决方案1】:

你需要...

  1. 阅读进程的Input/ErrorStream,这样,你就知道他们输出了什么。
  2. 使用Process#waitFor 来确定@​​987654323@ 何时完成,使用Thread.sleep 之类的东西只是自找麻烦。

因为你需要消耗两个进程的Input/ErrorStream,简单的事情就是写一个可以为你做的方法,所以你不需要重复代码

public static void main(String[] args) {
    try {
        ProcessBuilder pb = new ProcessBuilder("gcc", "calculator.c");
        pb.redirectErrorStream(true);

        Process compile = pb.start();
        consume(compile.getInputStream());

        int result = compile.waitFor();
        if (result == 0) {

            pb = new ProcessBuilder("./a.out");
            pb.redirectErrorStream(true);
            Process execte = pb.start();
            consume(execte.getInputStream());

            System.out.println("Program exited with " + execte.waitFor());

        } else {

            System.err.println("Compiler exited with " + result);

        }
    } catch (IOException | InterruptedException exp) {
        exp.printStackTrace();
    }
}

public static String consume(InputStream is) throws IOException {
    StringBuilder result = new StringBuilder(64);
    int in = -1;
    while ((in = is.read()) != -1) {
        result.append(result);
        // Technquially, you don't need this, but I like to have it as a check
        System.out.print((char) in);
    }
    return result.toString();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多