scott
scott

Reputation: 1637

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.

Upvotes: 0

Views: 1428

Answers (1)

Amir Afghani
Amir Afghani

Reputation: 38561

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?

Upvotes: 1

Related Questions