0

I have a console application written in c, it runs in the console and has its own pseudo-console. Through it, I configure this application and run it. All OK. Now I am trying to run this application inside a Java application, and I have problems. As an example, I use sh

ProcessBuilder builder = new ProcessBuilder("sh");
builder.redirectErrorStream(true);
Process process = builder.start();

try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
     BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()))) {

    bw.write("echo lol");

    while (true) {
        // System.out.println(process.isAlive());
        if (br.ready()) {
            System.out.println(br.readLine());
        }
    }
} catch (Exception ex) {
    ex.printStackTrace();
}

The main idea is to run the application in the console and send several commands to it.

deHaar
  • 17,687
  • 10
  • 38
  • 51

1 Answers1

0

So, after a few experiments, I get the answer.

    ProcessBuilder builder = new ProcessBuilder("sh");
    Process process = builder.start();


    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    new Thread(new Runnable() {
        public void run() {
            Scanner scan = new Scanner(br);
            while (true) {
                try {
                    if (!br.ready()) break;
                    System.out.println(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }).start();
    PrintWriter bw = new PrintWriter(process.getOutputStream());
    bw.println("echo Hello World");
    bw.println("echo lol");
    bw.flush();
    bw.close();