'How to run mongod process in background using Java Process Builder?

I'm trying to run a mongod process on a Linux host using Java ProcessBuilder API in a Spring Boot Application running on the same host. I tried the following ways.

Method 1 : Directly running mongod in bash

String confpath;
String []commands = {"./mongod","-f",confPath,"&"};
ProcessBuilder processBuilder = new ProcessBuilder(commands)
Process process = processBuilder.start();

Running a process with the above array makes ProcessBuilder take & as a mongod parameter and gives an error that & is not an option.

Method 2 : Using bash -c "command"


String exec = String.format("./mongod -f %s",confPath)
String []commands = {"/bin/bash","-c",String.format("\"%s\"",exec),"&"}
ProcessBuilder processBuilder = new ProcessBuilder(commands)
Process process = processBuilder.start();

This method exits with code 127 which means that this command wasn't found. I tried using absolute paths as well, Any insights would be helpful.

I'm running a JAR file if that helps.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source