Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: unexpected exception with Unix.getlogin when stdin redirected

Tags:

unix

ocaml

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?

like image 990
Ricardo Avatar asked Mar 20 '12 17:03

Ricardo


2 Answers

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.

like image 159
bkconrad Avatar answered Oct 18 '22 18:10

bkconrad


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.

like image 34
Fabrice Le Fessant Avatar answered Oct 18 '22 19:10

Fabrice Le Fessant