运行“谁-m” Java命令产生空结果 [英] Running "who -m" command from Java yields empty result
问题描述
我正在尝试从Java查找当前登录的用户名。
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)
{
}
上面的代码不显示任何结果。但是,如果我删除-m选项,它将显示用户名和其他详细信息。而且我还使用-s,-u等其他选项进行了测试。除-m外,所有其他功能均有效。有没有人知道为什么会这样?
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");
但这不是我的解决方案。我正在调用其中使用谁-m的shell脚本。因此,我不能使用Java类。
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.
推荐答案
您看到的原因是Java进程启动器不能保证是否存在关联的TTY。在实际的命令行上考虑以下示例:
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
$
由于标准输入未与第二个 who
呼叫的终端相关联,因此谁
无法确定关联的用户。有趣的是,将 stdin
重定向到 / dev / tty
似乎也不起作用:
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
$
说实话,除非确定与 stdin
相关的用户是准确,否则您应该可能会将您的脚本更新为使用主机名
,例如 id -un
或您的解释器可能会提供的其他手段来确定当前用户。
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.
这篇关于运行“谁-m” Java命令产生空结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!