Running “who -m” command from Java yields empty result

我们两清 提交于 2020-01-04 09:37:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!