Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In "C", I can run a long blocking process in the background (AND HAVE IT CONTINUE TO RUN) after the starting process has exited.

void main(void)
{
      system("some_long_blocking_process &");
      exit();
}

// "some_long_blocking_process" is still running here (DESIRED BEHAVIOR)

Java's getRuntime().exec() DOESN'T have this behavior. Instead, "some_long_blocking_process" ends immediately when the Java process ends.

Anyone know how I can recapture this behavior in Java?

  1. I am using Java 1.4 (No process builder)
  2. I specifically am looking to start the long blocking process and to exit immediately (no "waitFor(), etc.)
  3. Things I have already tried (the process runs correctly, but I still get the same undesired behavior)
    • adding "nohup" and run in foreground ("nohup some_long_process")
    • adding "nohup" and running in background ("nohup some_long_process &")
    • run in foreground ("some_long_process")
    • run in background ("some_long_process &")

THANKS!

Thanks to all the suggestions... I've decided to use jtahlborn's answer (it worked for me)

like image 521
casio car Avatar asked Oct 05 '11 17:10

casio car


2 Answers

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);
like image 178
bob Avatar answered Sep 26 '22 21:09

bob


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.

like image 36
jtahlborn Avatar answered Sep 26 '22 21:09

jtahlborn