OCaml: unexpected exception with Unix.getlogin when redirecting stdin

I found the following problem in this simple code:

let () = print_endline "Hello"; print_endline (Unix.getlogin ()) 

Running normally with ./a.out gives:

 Hello ricardo 

But working as ./a.out </dev/null makes Unix.getlogin fail:

 Hello Fatal error: exception Unix.Unix_error(20, "getlogin", "") 

Any idea why this is happening?

+6
source share
2 answers

Program input redirection overrides the control terminal. Without a control terminal, there is no login:

 $ tty /dev/pts/2 $ tty < /dev/null not a tty 

However, you can still find the username (possibly) by getting the user ID ( getuid ) and looking at his passwd record (related documents) ( getpwuid ), then finding your username in it.

+5
source

Depending on your application:

  • if you really don't care about the value returned by "getlogin", you can do something like:

     try Unix.getlogin () with _ -> Sys.getenv "USER" 

    you will probably get something better than getuid , as it will also work for programs with the Set-User-ID checkboxes (sudo / su).

  • if you really care about the value returned by getlogin, that is, you really want to know who is logging in, you should simply fail if getlogin fails. Any other solution will give you only a rough estimate of the correct result.

+3
source

Source: https://habr.com/ru/post/911226/


All Articles