Search code examples
javaprocessbuilder

Start Daemons from Java


Is it possible to start up a daemon from java. Specifically, I am trying to use MongoDB in java however I want my application to start up the mongod daemon if it not already running. I seem to be able to start it ok, exitcode is 0. However it always exits immediately. Is it possible to force it to stay running, then quit it with proc.destroy()?

ProcessBuilder pb = new ProcessBuilder("./bin/mongod","--dbpath data/db"); Process proc = pb.start();

If i set a breakpoint after i start the process the hasExisted boolean is always true, the exit code is 0 and I cannot connect to.

Also this is on OS X 10.5, I know ProcessBuilder is finicky across OS


Solution

  • Your command and path are probably not handled properly. Here is what needs to be done in pseudo java (groovy) to run mongodb after a fresh install with brew

    ProcessBuilder pb = new ProcessBuilder(["/usr/local/bin/mongod","run", "--config", "/usr/local/Cellar/mongodb/2.0.1-x86_64/mongod.conf"]); 
    
    Process process = pb.start()
    
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null) {
            System.out.println(line);
    }
        
    
    int exitValue = process.waitFor()
    print exitValue
    

    You can type the above directly in a groovy console.