codepleb
codepleb

Reputation: 10571

ProcessBuilder fails on command that includes local environment variable

I can execute usual commands on Linux, wrapped by the processBuilder. But I'm currently trying to run the minecraft server like in the following example, with some variable set before the command, and it fails with an exception.

final ProcessBuilder processBuilder = new ProcessBuilder("LD_LIBRARY_PATH=. ./bedrock_server");
processBuilder.directory(MC_PAL_LOCATION_DIR.toFile());
process = processBuilder.start();

Exception:

java.io.IOException: Cannot run program "LD_LIBRARY_PATH=. ./bedrock_server" (in directory "/home/user/Desktop/minecraft_bedrock_server_t"): error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at controller.Server.startMinecraftServer(Server.java:91)
    at controller.Server.start(Server.java:58)
    at Bootstrapper.bootServer(Bootstrapper.java:67)
    at Bootstrapper.main(Bootstrapper.java:30)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 4 more
Exception in thread "Thread-0" java.lang.NullPointerException
    at controller.ConsoleInput.run(ConsoleInput.java:16)
    at java.lang.Thread.run(Thread.java:748)

Is there any possibility to use the processBuilder for such commands? The command works if I paste it directly to the terminal.

Link to server: https://minecraft.net/en-us/download/server/bedrock/

Command: LD_LIBRARY_PATH=. ./bedrock_server

Upvotes: 3

Views: 407

Answers (2)

user10639668
user10639668

Reputation:

As @ElliottFrisch pointed out, you cannot use shell command without bash, therefore you either add LD_LIBRARY_PATH to environment map or execute bash:

    final ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c",  "LD_LIBRARY_PATH=. ./bedrock_server");
    processBuilder.directory(MC_PAL_LOCATION_DIR.toFile());
    process = processBuilder.start();

Upvotes: 4

Elliott Frisch
Elliott Frisch

Reputation: 201419

You can't use bash shell commands like that without bash. But you can manipulate the environment yourself programmatically. Like,

final ProcessBuilder processBuilder = new ProcessBuilder("./bedrock_server");
processBuilder.environment().put("LD_LIBRARY_PATH", ".");
processBuilder.directory(MC_PAL_LOCATION_DIR.toFile());
process = processBuilder.start();

Upvotes: 6

Related Questions