开发者

Java process is not terminating after starting an external process

开发者 https://www.devze.com 2022-12-28 06:46 出处:网络
On Windows I\'ve started a program \"async.cmd\" with a ProcessBuilder like this: ProcessBuilder processBuilder = new ProcessBuilder( \"async.cmd\" );

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 reader开发者_Go百科Thread.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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号