OCaml: unexpected exception with Unix.getlogin when stdin redirected OCaml: unexpected exception with Unix.getlogin when stdin redirected unix unix

OCaml: unexpected exception with Unix.getlogin when stdin redirected


Redirecting the input of a program overrides its controlling terminal. Without a controlling terminal, there is no login to be found:

$ tty/dev/pts/2$ tty < /dev/nullnot a tty

You can, however, still find a user's name (perhaps) by getting the user's id (getuid) and looking up his passwd entry (related docs) (getpwuid), then finding his username in it.


Depending on your application:

  • if you don't really 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, since it will also work for programs with Set-User-ID flags (sudo/su).

  • if you really care about the value returned by "getlogin", i.e. you really want to know who is logged in, you should just fail when getlogin fails. Any other solution will give you only an approximation of the correct result.