1

I need to find the logged in user from the java code, so i use following options: Runtime.getRuntime.exec("who") Runtime.getRuntime.exec("who am i")

Both give same result (the result that i get when i give who command on the prompt). I guess it is not recognising anything after space. I tried it with other commands too but same result.

Is there a problem with code or i need to set some environment, plz help.

doubter
  • 11
  • 2
  • See http://stackoverflow.com/questions/525212/how-to-run-unix-shell-script-from-java-code – stacker Feb 05 '12 at 08:37
  • The command `whoami` might be more useful. It gives you just the user's name. Also, most shells define an environment variable called USER. It's accessible through `System.getProperty("user.name")`. – jackrabbit Feb 05 '12 at 09:13
  • And, as an aside, this approach returns the owner of the java process. If you are writing an application that the user has to log in to, and you want to get that user id, then this is not going to give you what you want. – DaveH Feb 05 '12 at 10:05

2 Answers2

2

The Runtime.exec() function's first parameter only takes the program name.

In order to pass arguments along, you need to use a different version, such as Runtime.exec(String[] cmdarray). Example:

Runtime.getRuntime().exec(new String[] {"who", "am", "i"} );

Or, more easily:

Runtime.getRuntime().exec("who am i".split());

Which uses the String.split() method to split on spaces.

Raceimaztion
  • 9,494
  • 4
  • 26
  • 41
  • On second read, I was wrong. From the [docs](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html#exec%28java.lang.String,%20java.lang.String[],%20java.io.File%29), "More precisely, the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order. " Also, `getRuntime` is a method. – Matthew Flaschen Feb 05 '12 at 08:50
2

If you just need to know the name of the currently logged in user, and none of the other information of the who command (like the pty name, etc.), you should use

System.getProperty("user.name"); 

This way you stay platform independent, locale independent (the format of the output of who am i may be different if you're not using the C locale) and it is much more robust then invoking an external command.

Christian.K
  • 47,778
  • 10
  • 99
  • 143