Runtime.getRunTime().exec not behaving like C language “system()” command

空扰寡人 提交于 2019-12-01 06:26:02

the only way we were able to achieve this with java was to add another layer of script. you need a simple wrapper script which invokes the app you actually want to run, e.g.:

runner.sh:

#!/bin/sh

nohup "$@" > /dev/null 2>&1 &

then invoke "/bin/sh runner.sh the real command" from your java program.

try this:

String[] cmd = {"/bin/sh", "-c", "yourcommand args"};
Process p = Runtime.getRuntime().exec(cmd);

when redirect stream to /dev/null:

String[] cmd = {"/bin/sh", "-c", "yourcommand args > /dev/null 2>&1 &"};
Process p = Runtime.getRuntime().exec(cmd);

EDIT:

Have your tried this?

Runtime.getRuntime().exec("/bin/sh -c /usr/X11/bin/xterm &")

This worked for me on MacOS.

Previous answer (JDK 1.5, apologies for not reading the question correctly):

To execute a process without waiting you can use the ProcessBuilder

ProcessBuilder pb = new ProcessBuilder("/usr/X11/bin/xterm");
pb.start();

Your problem is probably due to the trailing &. Try removing it.

getRuntime().exec() is more similar to fork() and exec() than system().

system() passes the command to the shell, and it's Bash that understands that the trailing ampersand means to run the process in the background.

getRuntime().exec() parses the command using a StringTokenizer to parse the command, and doesn't do anything with the trailing ampersand. That's simply passed as the first argument to your some_long_blocking_process, which may exit out immediately on the unknown error.

Have you tried spawning a new Thread to run the executable? Try:

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Runtime.getRuntime().exec(<your exec>);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).run();

This way, the main process won't shutdown until the exec has finished running (and the thread has finished).

Also, don't manually call exit() in your application unless you have some overwhelming reason to--the JVM does a good job of detecting when the application has finished on its own. This way, you won't force close threads that are running in the background.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!