Support Wikipedia Follow My Heart: Why java hang when invoking WMIC command

2011年10月6日星期四

Why java hang when invoking WMIC command

Today I want to invoke WMIC command from java program (through Runtim

e.getRuntime().exec(.....)).


I use the following code, but unfortunately, my java appears to "deadlock".
public void testWMIC(){
	final String command = "cmd /c wmic.exe Process get processid /format:csv";
	ProcessExecutor executor = new ProcessExecutor(command, ProcessExecutor.class);
	executor.start();
	executor.waitFor(500);
}

I search many web sites, read the instructions about how to use Runtime.exec() in Java, but there was no hint for this issue.

Finally, I found a website, which said that sometimes the program invoked by command does NOT "Stop".

Although I feel it is ridiculous, I tried the following command. This time everything works OK.

final String command = "cmd /c wmic.exe Process get processid /format:csv <NUL";



Reference Code 1

Reference Code


Reference Code 2

Reference Code

1 条评论:

  1. The reason why Java programmers need "<NUL" is that the program should explicitly close the output Stream of new created process. Unless the WMIC tool will not be executed.

    So in other words, you can also use the following code to run WMIC in java:

    String command = "cmd /c wmic ..... ";
    Process process = getRuntime().exec(command);
    process.getOutputStream().close();
    .... (continue on redirecting inputstream and errorstream to your own printstreams)

    回复删除