简体   繁体   中英

OCaml: unexpected exception with Unix.getlogin when stdin redirected

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", ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM