I found out the next issue in this simple code:
let () =
print_endline "Hello";
print_endline (Unix.getlogin ())
Running in the normal case, with ./a.out
gives:
Hello
ricardo
But running like ./a.out </dev/null
makes Unix.getlogin fail:
Hello
Fatal error: exception Unix.Unix_error(20, "getlogin", "")
Any idea why this happens?
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/null
not 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With