简体   繁体   中英

Java Runtime.getRuntime.exec() returns null but returns valid String in shell

I've been writing a class to find the real userID, using the linux binary /usr/bin/logname that returns the current user associated with my TTY. The command works fine in shell.

/usr/bin/logname
scott

But I cannot get the same as a String in java with the following code that I wrote.

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);
}

When I create the object, I am seeing null for the value currentUser , which means stdInput.readLine(); is not outputting anything.

Please let me know what am I doing wrong.

This is not answering your question directly, but did you try :

System.getProperty("user.name") 

which is at least platform agnostic? Why bother writing code thats unix specific in a language like Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM