DesirePRG
DesirePRG

Reputation: 6378

Couldn't read stream from external process

Following is my program which I wrote in order to start a process in linux and print the result in console.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Driver {
    public static void main(String[] args) {
        try {
            Process process = new ProcessBuilder("/usr/bin/R").start();
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;

            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I am expecting that the R version and other stuff which will be displayed when I start R in terminal, to be printed in the console. But nothing gets printed and there is no exception.

What is the issue here?

EDIT

My program above works when I use a command like "ls" or "ps". but not for any command which doesn't exit by its own

Upvotes: 1

Views: 69

Answers (1)

Nikita Skvortsov
Nikita Skvortsov

Reputation: 4923

As the process is started in a separate thread, br may just have wrong state when execution reaches the loop.

Primitive solution: if you do not need to interact with started process, you can add process.waitFor() before the loop to make sure the process has finished and output is available.

In general, interaction with external process will require separate threads to monitor its state, read std out and std err streams. In this case, it makes sense to use a library solution, e.g. Apache Commons Exec (see the tutorial)

Upvotes: 2

Related Questions