0

I am trying to execute a label cmd comand from java, but when I call exec and wait for the end of the process it freezes. What do you think is the problem?

    String[] comand = {"cmd.exe","label D: CIAO"};
    Runtime rt = Runtime.getRuntime();
    Process proc;

    try {
        proc = rt.exec(comand);     
        int exitCode=proc.waitFor();
        System.out.println(exitCode);
    } catch (IOException e) {
        e.printStackTrace();
Sceik
  • 275
  • 1
  • 3
  • 13
  • 1
    More than likely, your process writes a lot of stuff to stdout; but it blocks because it cannot write anymore. You need to read from this process' output. Also, use a `ProcessBuilder`, not `Runtime.exec()`. – fge Feb 26 '14 at 16:37
  • Check your task manager to make sure the process (cmd.exe) has actually exited. – Ted Bigham Feb 26 '14 at 16:39
  • Did you execute the same command manually from commandline? Does it take more time to execute with the same options/input? I suspect the executable takes longer to finish, which gives an impression that program freezes. – 18bytes Feb 26 '14 at 16:40
  • in DOS too 'cmd' does not return; you should run `cmd /C command` (check cmd.exe /?) – robermann Feb 26 '14 at 16:41
  • Out of the question : You can use [Apache commons exec](http://stackoverflow.com/a/21793314/1686291) – Not a bug Feb 26 '14 at 17:12

1 Answers1

0

Remember, if you just execute the CMD or COMMAND by itself it will start it own "shell" window and will not return. You have to use the /c to tell it to execute the command and return. For Windowz NT and better it should be CMD.exe /c your_command and for Windowsz 95 or worst, it should be COMMAND.com /c your_command and to check use the following Java codes:

String os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("windows 9") > -1) {
  cmd = "CMD.exe /c";
} else if ((os.indexOf("nt") > -1) || (os.indexOf("windows 2000") > -1) || (os.indexOf("windows xp") > -1)) {
  cmd = "COMMAND.com /c";
}
TA Nguyen
  • 453
  • 1
  • 3
  • 8