问题
I am trying to find the current logged in username from Java.
Process p;
try
{
p = Runtime.getRuntime().exec("who -m");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null)
System.out.println(line);
}
catch (Exception e)
{
}
The above code does not print any result. However if i remove -m option, it prints user name and other details. And also i tested with other options like -s, -u. It all works except -m. Does anyone has an idea why is it so?
Note: I am aware of
System.getProperty("user.name");
But that's not a solution in my case. I am calling a shell script in which "who -m" is used. So, I cannot use java classes.
回答1:
The reason for what you are seeing is that the Java process launcher does not guarantee the existence of an associated TTY. Consider this example on the actual command line:
$ who -m
user pts/8 2014-09-02 02:24
$ who -m </dev/null
$
Since the standard input is not associated with a terminal for the second who
call, who
cannot determine the associated user. Interestingly enough, redirecting stdin
to /dev/tty
does not appear to work either:
$ who -m </dev/tty
$
Quite honestly, unless determining the user associated with stdin
is exactly what you are after, you should probably update your script to use hostname
and e.g. id -un
or whatever other means your shell interpretter may offer to determine the current user.
For those interested in the details, I did a little bit more digging for another answer of mine.
回答2:
From the man page for who:
"-m only hostname and user associated with stdin"
I gather that this means the who command knows the current user based on a "who just hit the return key?" criteria. Given that you are running the command from the JVM, I would entirely expect something weird to happen.
If you're using a bash script, try this as a work around.
process=`ps | grep ps | cut -d ' ' -f2`
user=`who -u | grep $process | cut -d ' ' -f1`
Unfortunately I've never tried to make java and bash work togeather, sorry I cant be more helpful!
来源:https://stackoverflow.com/questions/26123706/running-who-m-command-from-java-yields-empty-result