0

I need to write an application in java(Windows) that will run the pgbench command with the -P parameter and read the output from the console.

I wrote .bat file "windowsPostgr.bat":

set "PGUSER=postgres" set "PGPASSWORD=postgres" pgbench -c 1 -f C:/work/EasySQL.sql -j 1 -t 1500 -P 1 -U postgres mydb

And my code:

String cmd = "cmd /c C:\\windowsPostgr.bat";
Process process = Runtime.getRuntime().exec(cmd);

try {

    BufferedReader reader =
            new BufferedReader(new InputStreamReader(process.getInputStream()));

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

    int exitCode = process.waitFor();
    System.out.println("\nExited with error code : " + exitCode);

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

As a result, when run jar in cmd, only the resulting pgbenh information is shown:

transaction type: Custom query scaling factor: 1 query mode: simple number of clients: 1 number of threads: 1 number of transactions per client: 1500 number of transactions actually processed: 1500/1500 latency average: 11.181 ms latency stddev: 1.200 ms tps = 89.073332 (including connections establishing) tps = 89.404427 (excluding connections establishing)

Whereas, when windowsPostgr.bat is started by handles, additional information is displayed (due to the -P parameter) of the form:

progress: 1.0 s, 76.8 tps, lat 12.147 ms stddev 1.356

progress: 2.0 s, 84.1 tps, lat 11.864 ms stddev 1.034 etc

Actually the question: how to display additional information when running windowsPostgr.bat from IDEA or jar? and will reader.readLine () read and display this information?

1 Answers1

1

The additional information you do not read from java are actually printed to stderr, not stdout, that is why you do not read it.

If you want this information you must capture stderr of the process using getErrorStream().

Edit: read this: Java Process with Input/Output Stream

It's even easier to use a ProcessBuilder instead of Runtime.getRuntime().exec(cmd) to start your process and then just redirect error stream to output stream using builder.redirectErrorStream(true);. This way you will get everything in the right order.

StephaneM
  • 4,779
  • 1
  • 16
  • 33
  • Thank you! I added getErrorStream() and got the missing information. But it is necessary to display information in the same sequence as in the command line. Now the information is displayed on the streams first getInputStream(), then later getErrorStream() – Kolka Kola May 06 '19 at 09:55
  • I've update my answer with a link showing how to get everything in the right order. – StephaneM May 06 '19 at 12:11