【发布时间】:2015-11-24 19:13:39
【问题描述】:
我一直在编写一个类来查找真正的用户 ID,使用 linux 二进制文件 /usr/bin/logname 返回与我的 TTY 关联的当前用户。该命令在 shell 中运行良好。
/usr/bin/logname
scott
但我无法使用我编写的以下代码在 java 中获得与 String 相同的结果。
private String currentUser;
public void getRealUser() throws Exception{
String cmd = "/usr/bin/logname";
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
this.currentUser = stdInput.readLine();
System.out.println(currentUser);
}
当我创建对象时,我看到 null 的值是 currentUser,这意味着 stdInput.readLine(); 没有输出任何东西。
请让我知道我做错了什么。
【问题讨论】:
-
我有一个类似的应用程序,但我在
p.waitFor();之前读取了输入内容您是否尝试将p.waitFor();放在System.out.println之前? -
是的。在
System.out.println()之后仍然是null和p.waitFor() -
我的意思是在
this.currentUser =语句之后,但在System.out.语句之前。另一方面,您得到的第一行可能是空行...我使用while循环来确保我读取了InputStream中的所有行。 -
适合我...
-
@Jan 来自 ideone.com 链接 4 cmets 以上。 - scott 这不是 java 问题,在某些情况下我会在终端中遇到同样的错误。该错误的含义类似于:您的 shell 命令在登录 shell 中运行,而 java 则没有(从 java 生成的子进程)。或者aplawrence.com/Forum/TonyLawrence8.html - 换句话说,linux 有时不知道用户是如何负责一个进程的 $LOGNAME 或 $USERNAME 或者可能有一个值,但它们也不可靠
标签: java linux shell runtime.exec