Java Runtime执行C语言程序得不到输出 [英] Java Runtime execute C language program get no output

查看:658
本文介绍了Java Runtime执行C语言程序得不到输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的C程序,并将其构建为AskStack.exe。

I write a simple C program, and build it to "AskStack.exe".

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello world!\n");
    getchar();
    return 0;
}

然后我使用java程序来执行C程序,我想要得到输出。

and then i use the java program to exec the C program, i want to get the output.

import java.io.BufferedReader;
import java.io.InputStreamReader;


public class Test {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        Process p = Runtime.getRuntime().exec("AskStack.exe");
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        do{
            line = reader.readLine();
            System.out.println(line);
        }while(line != null);
        p.waitFor();
    }

}

但我失败了。 java程序没有输出任何东西。
我注意到如果我删除C程序的getchar(),它将获得输出。
但我的目的是与C程序进行交互。

but i failed. the java program did not output anything. i note that if i remove the getchar() of the C program, it will get the output. But my purpose is to interact with the C program.

那么我应该如何修改我的java代码?提前谢谢。

So how should i modify my java code? thanks in advance.

推荐答案

以下是发生的事情。


  1. Java程序启动AskMe.exe程序。

  1. The Java program launches the AskMe.exe program.

AskMe.exe将一行写入stdout的输出缓冲区

The AskMe.exe writes a line to the output buffer for stdout

AskMe.exe调用 getChar 阻止等待标准输入的字符。

The AskMe.exe calls getChar which blocks waiting for a character on its standard input.

同时


  1. Java程序尝试从子进程标准输出中读取一行。

死锁!

问题是AskMe.exe还没有刷新标准输出缓冲区。直到它退出后它才会这样做...它已经读过永远不会到达的角色!

The problem is that AskMe.exe has not flushed the standard output buffer yet. And it won't do that until it exits ... after it has read the character that is never going to arrive!

有很多可能的修复,包括以下内容:

There are a number of possible fixes, including the following:


  • 您可以删除 getChar()调用。

您可以在 printf stdout 流C $ C>。 (但这只是将bug移到另一个地方。现在Java程序将读取然后打印hello world消息,然后等待子进程退出...这将永远不会发生。)

You could explicitly flush the stdout stream after the printf. (But that just moves the bug to another place. The Java program will now read and then print "hello world" message, and then wait for the the child process to exit ... which won't ever happen.)

您可以修改Java程序以将字符写入子进程标准输入。如果你不修改AskeMe.exe,那么必须在Java程序试图从孩子那里读取之前完成...或者你将再次陷入僵局。

You could modify the Java program to write a character to child processes standard input. If you don't modify AskeMe.exe, this has to be done BEFORE the Java program attempts to read from the child ... or you will deadlock, again.

这篇关于Java Runtime执行C语言程序得不到输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆