1

I'm running on Ubuntu. I have Java a program being started from command line using java -jar myTopJar.jar. The myTopJar.jar should do something and than , run a second jar and terminate (the myTopJar.jar should terminate and let the second jar run).

In order to run a jar and disowning it (I mean from command line) I used to run this command: java -jar mySecondJar.jar & disown.

I expected the same behaviour when I run the command from Java utility that I'm using :

import org.apache.commons.exec.*;

public static int execCommand () throws ExecuteException, IOException, InterruptedException {
    logger.debug("About to execute command: ", command);
    CommandLine commandLine = CommandLine.parse("java -jar mySecondJar.jar & disown");
    DefaultExecutor executor = new DefaultExecutor();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(commandLine, resultHandler);
    return 0;
}

I'm using Apache's commons-exec-1.2.jar Just to make the flow clear:

  1. I'm running the myToJar.jar from Linux command line
  2. The last line in the main() method of myTopJar.jar should call the above execCommand() method and exit (expecting the mySecondJar.jar to continue running).

The result is that myTopJar.jar termination, terminates the mySecondJar.jar process as well.

Can someone please assist here?

Modi
  • 2,200
  • 4
  • 23
  • 37

1 Answers1

0

Why don't you make a wrapper for your second call. The wrapper will make the second process a daemon properly using a double-fork technique so that the second process will have no connection to the session of the first one. I would write a wrapper in C using daemon(3) function if it's available on the system you are going to use.

For example you can use the following simple C code for your wrapper:

#include <stdio.h>
#include <unistd.h>

int main()
{
        if (0 != daemon(1, 0)) { /* 1 for nochdir */
                perror("daemon");
                return 1;
        }

        if (0 != execl("/path/to/java", "/path/to/java", "-jar", "mySecondJar.jar", NULL)) {
                perror("execl");
                return 1;
        }

        /* not reached */
        return 0;
}

Compile it and call from your first Java program.

Community
  • 1
  • 1
afenster
  • 3,468
  • 19
  • 26