Run consecutive Commands Linux with java runtime exec
java, linux, runtime
Solution
As stated in the Javadoc for Runtime.exec():
Executes the specified string command in a separate process.
each time you execute a command via exec() it will be executed in a separate subprocess. This also means that the effect of su ceases to exist immediately upon return, and that's why the `whoami` command will be executed in another subprocess, again using the user that initially launched the program.
su test -c whoami
will give you the result you want.
Problem
I need to run two commands Linux using java code like this: ``` Runtime rt = Runtime.getRuntime(); Process pr=rt.exec("su - test"); String line=null; BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); while((line=input.readLine()) != null) { System.out.println(line); } pr = rt.exec("whoami"); input = new BufferedReader(new InputStreamReader(pr.getInputStream())); line=null; while((line=input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Exited with error code "+exitVal); } catch(Exception e) { System.out.println(e.toString()); e.printStackTrace(); } ``` The problem is the output of the second command ("whoami") doesn't display the current user which used on the first command ("su - test")! Is there any problem on this code please?