Skip to content
Advertisement

Parse command `watch` with `InputStream`

I have this command:

new ProcessBuilder()
    .command("watch", "-n2", "ps", "-q", IdeProcess.pid, "-o", "rss");

How I can to parse output from this command?

When I get InputStream of this Process, I get an empty line every time.


I used to restart the command via Java, creating a new thread and all over again. Now, I decided to implement it with the help of watch.

Snippet of code:

var process = processBuilder.start();
var stream = process.getInputStream();
var input = new StringBuilder();
int n;

//while (isOpenIO) {
    while ((n = stream.read()) != -1)
        input.append((char) n);
    if (input.length() > 0)
        System.out.println("NON EMPTY");
    if (input.length() > 3) {
        String text = input.substring(input.indexOf("n") + 1, input.length() - 1);
        String modified = text.replaceAll("\B(?=(\d{3})+(?!\d))", ",");
        System.out.println("RAM: " + modified + " Mb"));
    }
//}

Advertisement

Answer

A very crude example of something like what you want to achieve is the following. This uses a single threaded executor service running at 2 seconds intervals, polling the memory usage of a given process.

At the moment this only prints the result out to the console, but you can tinker around with it to return a Future so you can get your result.

I hope this helps.

private static ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    public static void main(String[] args) {
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            try {
                Process process = new ProcessBuilder("ps", "-p", "2782", "-o", "%mem").redirectErrorStream(true).start();
                try(BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                    String s = reader.lines().collect(Collectors.joining("n"));
                    System.out.println(s);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 0, 2, TimeUnit.SECONDS);
    }

For reference, I’m using ps here to get the memory usage of the process in question, but you can use whatever you like.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement