java - C 程序在运行时执行 shell 相对于 JAVA 中的输入和输出

标签 java c runtime exec output

import java.io.*;
import java.util.Scanner;

public class runtime {

    public static void main ( String [] args) {
        try {
            Process proc= Runtime.getRuntime().exec("bash -c " + "./a.out" ); 
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedWriter stdOutput = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
            String s = "";
            BufferedReader reader = new BufferedReader((new InputStreamReader(System.in)));
            String sendMemo = reader.readLine();
            stdOutput.write(sendMemo+"\n");
            stdOutput.flush();
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }           
        }
        catch( IOException e ) { System.out.println ( e )};         
    }
}

C代码

#include<stdio.h>
int main()
{
    int a;
    printf("InPUt : \n");
    scanf("%d",&a);
    printf("std : %d",a);   
}

我想在JAVA中执行C程序。我想使用来自 JAVA 的 shell 命令:

 runtime.getRuntime().exec

所以我想要这样的结果:

print :: Input :     <-value input 5
print ::std : 5

但是 我的代码是

value input 5
print :: Input :
print :: std : 5

请帮帮我

最佳答案

您的 Java 程序从标准输入读取“5”,这是尽职尽责地回显,因为标准输入是终端。

然后,您通过管道将其传递到被调用的 C 程序的标准输入。这个管道不再是终端,所以没有回声;包含“5”的行在没有回显的情况下被读取并被处理。因此您将看到提示(“InPUt”),但没有回显。

关于java - C 程序在运行时执行 shell 相对于 JAVA 中的输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24954978/

相关文章:

java - 读取 persistence.xml 文件中的 PropertyPlaceholderConfigurer

c - 不正确的二叉树

java - shell脚本与java运行时不一致

javascript - 如何在运行时修改 javascript 代码?

java - Spring + Hibernate + Maven org.hibernate.MappingException : AnnotationConfiguration instance is required

java - 这个 Singleton 是线程安全的吗?我看不出来怎么办?

C数组元素改变值

c - 如何在 FFmpeg 中模拟 OpenFile?

c++ - 降低构建大小

java - Eclipse 的声明 View 有什么用?