views:

214

answers:

1

On Windows I've started a program "async.cmd" with a ProcessBuilder like this:

ProcessBuilder processBuilder = new ProcessBuilder( "async.cmd" );
processBuilder.redirectErrorStream( true );
processBuilder.start();

Then I read the output of the process in a separate thread like this:

byte[] buffer = new byte[ 8192 ];
while( !interrupted() ) {
    int available = m_inputStream.available();
    if( available == 0 ) {
        Thread.sleep( 100 );
        continue;
    }

    int len = Math.min( buffer.length, available );
    len = m_inputStream.read( buffer, 0, len );
    if( len == -1 ) {
        throw new CX_InternalError();
    }
    String outString = new String( buffer, 0, len );
    m_output.append( outString );
}

Now it happened that the content of the file "async.cmd" was this:

REM start a command window 
start cmd /k

The process that started this extenal program terminated (process.waitFor() returned the exit value). Then I sent an readerThread.interrupt() to the reader thread and the thread terminated, too.

But there was still a thread running that wasn't terminating. This thread kept my java application running even if it exited its main method. With the debugger (eclipse) I wasn't able to suspend this thread. After I quit the opened command window, my java program exited, too.

Question

How can I quit my java program while the command window stays open?

+1  A: 

You can use System.exit(0) method after you know that child process was finished (e.g. after process.waitFor() returned the exit value). This method will exit the application anyway with no regards to the background threads.

ruslan