简体   繁体   English

OCaml:当stdin重定向时,Unix.getlogin出现意外异常

[英]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: 在正常情况下运行,使用./a.out给出:

Hello
ricardo

But running like ./a.out </dev/null makes Unix.getlogin fail: 但是像./a.out </dev/null一样运行会使Unix.getlogin失败:

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. 但是,您仍然可以通过获取用户的id( getuid )并查找其passwd条目(相关文档)getpwuid ),然后在其中查找用户名来查找用户名(可能)。

Depending on your application: 取决于您的应用:

  • if you don't really care about the value returned by "getlogin", you can do something like: 如果你真的不关心“getlogin”返回的值,你可以这样做:

     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). 你可能会得到比getuid更好的东西,因为它也适用于具有Set-User-ID标志(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. 如果你真的关心“getlogin”返回的值,即你真的想知道谁登录了,你应该在getlogin失败时失败。 Any other solution will give you only an approximation of the correct result. 任何其他解决方案只会给出正确结果的近似值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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