Search code examples
javalinuxprocessbuilder

switch user in Process Builder


I want to switch user and then launch a command under the new user. Actually my code is

String[] commandToRun2 = {"su","-","jboss", "./jboss-cli.sh -c :shutdown(restart=true)"};
ProcessBuilder pb = new ProcessBuilder(commandToRun2);
pb.directory(new File("/home/jboss/soft/jboss-as-7.1.1.Final/bin/"));
Process p = pb.start();

but I can't make it work.


Solution

  • According to this SuperUser answer, your call to su doesn't appear to be quite right.

    From that question, the su command should have the form

    su [username] -c "[command]"
    

    So, try the following instead:

    String[] commandToRun2 = {"su", "jboss", "-c", "./jboss-cli.sh -c :shutdown(restart=true)"};
    

    Incidentally, it may be helpful to log any output written to the process's standard output and standard error. If there's an error, you'll then be able to see what the error is, and if the process generates a lot of output, reading the output will prevent output buffers from filling and blocking the process. This answer demonstrates how you can do this.