The windows process executed by the java process did not terminate

I create a process on windows from Java My problem is that this process will not end This is an example program:

import java.io.IOException;

public class Test {

/**
 * @param args
 * @throws IOException
 * @throws InterruptedException
 */
public static void main(String[] args) throws IOException,InterruptedException {
    Process process = Runtime.getRuntime().exec("cmd /c dir");
    process.waitFor();
    }
}

To exceed my understanding, the program will never be completed If "CMD / C dir" is replaced by ipconfig and other things, this is true

I can see that the CMD process is created in Java using process explorer This sample is obviously a simplification; In my original program, I found that if I call process. after a while, Destroy() and check the CMD process output, then the command will be executed successfully

I have tried various versions of Java 1.5 and 1.6 My operating system is Windows XP pro, SP 2

Solution

Most likely, you only need to read stdout and stderr of the process, otherwise it will hang when the output buffer is full If you redirect stderr to stdout, this is the simplest, just for security reasons:

public static void main(String[] args) throws IOException,InterruptedException {
        String[] cmd = new String[] { "cmd.exe","/C","dir","2>&1" };
        Process process = Runtime.getRuntime().exec(cmd);
        InputStream stdout = process.getInputStream();
        while( stdout.read() >= 0 ) { ; }
        process.waitFor();
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>