Hi,
I have written a class that handles stdout and std err from a unix
command. How can I make sure that both threads have finished? Do I need
to synchronzie my StreamConverter?
cheers,
//mikael
> public class RuntimeExec {
>
> public RuntimeExec() {
> }
>
> /**
> * Executes a command
> * @param command
> * @return The result of the command
> * @throws IOException
> */
> public String exec(String command) throws IOException {
> int exitValue = 0;//0 - executed ok.
> String stdOut = null;
> String stdErr = null;
> String result = null;//result from clearcase operation
> StringBuffer out = new StringBuffer();
> StringBuffer err = new StringBuffer();
> Process process = Runtime.getRuntime().exec(command);
> StreamConverter outSc = new StreamConverter(process.getInputStream(),out);
> StreamConverter errSc = new StreamConverter(process.getErrorStream(),err);
> Thread outThread = new Thread(outSc);
> Thread errThread = new Thread(errSc);
> outThread.start();
> errThread.start();
> //Wait until the prosess finish
>
> long delayMillis = 5000; // 5 seconds
> try {
> //wait for threads to die.
> outThread.join(delayMillis);
> if (outThread.isAlive()) {
> // Timeout occurred; thread has not finished
> } else {
> // Finished
> }
> } catch (InterruptedException e) {
> // Thread was interrupted
> }
>
>
>
>
> return result;
>
>
> }
>
> // bridge between byte and character stream.
> class StreamConverter implements Runnable {
> private InputStreamReader isr = null;
> private StringBuffer sb = null;
> // end of steam
> private static final int EOS = -1;
>
> public StreamConverter(InputStream is, StringBuffer sb) {
> isr = new InputStreamReader(is);
> this.sb = sb;
> }
>
> public void run() {
> int character = 0;
> try{
> while ((character = isr.read()) != EOS) {
> sb.append((char)character);
> }
> }catch(IOException ioe){
> System.out.println("Could not read std out!"+ioe.getMessage());
> }
> }
>
> }
>
>
> }
Gordon Beaton - 25 Oct 2006 11:25 GMT
> I have written a class that handles stdout and std err from a unix
> command. How can I make sure that both threads have finished? Do I
> need to synchronzie my StreamConverter?
Thread.join() without a timeout will wait until the thread has
finished. All you need to do is the following:
outThread.join();
errThread.join();
After that, both threads have terminated.
/gordon

Signature
[ don't email me support questions or followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e