0

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.

11
  • I have a similar app, but I read the input before p.waitFor(); Have you tried putting p.waitFor(); before the System.out.println ? Commented Nov 24, 2015 at 19:18
  • Yes. It is still null with p.waitFor() after System.out.println() Commented Nov 24, 2015 at 19:21
  • I meant after the this.currentUser = statement, but before the System.out. statement. On another note, there's the potential that the first line you get is a null line... I use a while loop to make sure I read all lines from the InputStream. Commented Nov 24, 2015 at 19:24
  • 1
    Works correctly for me... Commented Nov 24, 2015 at 19:38
  • 1
    @Jan that was the one from the ideone.com link 4 comments above. - scott that's not a java problem, I get the same error in the terminal in some cases. The error means something like: your shell command runs in a login shell while the java one doesn't (the subprocess spawned from the java one). Or aplawrence.com/Forum/TonyLawrence8.html - in other words, linux sometimes doesn't know how the user is that's responsible for a process $LOGNAME or $USERNAME orso may have a value but they aren't reliable either Commented Nov 25, 2015 at 10:59

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that will, but that will defeat the purpose of getting the real username, but returns the effective username. If I run the program as sudo, it will return root, but if I run /usr/bin/logname as sudo, it will return the real user, not root.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.