Pergunta

I want my application to run xterm shell and run a command "hg clone". I can't understand why the same command works perfectly when I type it directly to xterm and doesn't work when my program uses:

Process p = Runtime.getRuntime().exec(command);

where command is:

"xterm -e " + "'hg --debug -v clone ssh://" + host + "/ "+ src + " " + dst + " ; read ;'"

xterm opens and I get:

xterm: Can't execvp: "hg: No such file or directory

Could you help me,please?

Foi útil?

Solução

The short answer is that exec(String) doesn't understand quotes.

Your expression:

"xterm -e " + "'hg --debug -v clone ssh://" + host + "/ " + 
        src + " " + dst + " ; read ;'"

is going to give you a string something like this:

"xterm -e 'hg --debug -v clone ssh://host/src dst; read ;'"

That is going to be split into a command and arguments equivalent to this:

new String[] {"xterm", "-e", "'hg", "--debug", "-v", "clone",
 "ssh://host/src", "dst;", "read", ";'"}

... which is garbage. (It tells xterm to run the 'hg command!)

The problem is that the exec(String) uses a niave scheme for "parsing" the command line string. It simply splits on multiples of one or more whitespace characters ... treating any embedded quotes and other shell meta characters as data.

The solution is to do the command / argument splitting yourself; e.g.

Process p = Runtime.getRuntime().exec(new String[]{
        "xterm",
        "-e",
        "'hg --debug -v clone ssh://" + host + "/ " + 
                src + " " + dst + " ; read ;'"});

Now I get error "Cannot run program "x-term": error = 2, No such file or directory"

  1. The program is "xterm", not "x-term". (You managed to get it right before ...)

  2. If that is not the problem, try using the absolute pathname the program.

  3. Either way, it is a good idea to try to understand the error message. In this case, the error message plainly tells you that it cannot run the program ... and it tells you the name of the program that it cannot run.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top