ATEF CHAREF ATEF CHAREF - 1 year ago 159
Linux Question

Run consecutive Commands Linux with java runtime exec

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) {

pr = rt.exec("whoami");
input = new BufferedReader(new InputStreamReader(pr.getInputStream()));


while((line=input.readLine()) != null) {
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {

The problem is the output of the second command ("whoami") doesn't display the current user wich used on the first command ("su - test")!!
is there any problem on this code please??

fvu fvu
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download