Click to See Complete Forum and Search --> : How to read process output correctly?


emirc
January 30th, 2004, 05:41 AM
Hi,
I've tried to use Process class to create a utility that would start a native process (tested with Windows diskpart.exe) and to get output and write some commands to the process.
I got into trouble.
I'm using BufferedReader readLine() get the output and writing to process stdin using OutputStream.
Here is the scenario:
1. read all from process intial output
in diskpart.exe this would be


Microsoft DiskPart version 1.0
Copyright (C) 1999-2001 Microsoft Corporation.
On computer: OBJECT

DISKPART>

2. send to process "exit\r\n"

3. get any messages from program on levaing
here this would be

DISKPART> exit

Leaving DiskPart...


So to perform the first step I use the
while((line=bin.readLine()) != null)
condition and inside the loop I simply println(line).

But, the program hangs after reading the first three lines of program output hangs, and the DISKPART> prompt is never read!??!

Anyway, the general question would be:
How to properly communicate with a native process started using Runtime/Process combination?!
Is there a tutorial on the subject somewhere?!

cjard
February 2nd, 2004, 04:45 AM
you probably DONT want to use a buffered reader for this, you see:

DISKPART>

is a prompt.. anything you type appears NEXT TO diskpart>, not under it.. hence is has NO newline character present, so your bufrdr.readLine() method CANNOT pick up a new line, so it blocks (intentionally) waiting for a new line to appear

I suggest you use a buffered input stream, wrapped on an inputstream reader, wrapped on the output of the process..
Read the characters into a char/byte array and the read(array, offset, length) method will tell you the number of bytes read, so there defining your array limits.
Examine the array for what you want, then if it contains "diskpart>" you can start writing to the process's standard input (STDIN) using the available inputstreams.
It may be enought o send a \n character on Microsoft systems, \r\n may not be necessary. (i think ctrl+M is just a \n, and it works ina dos box to write javac MyClass.java[ctrl+M])