[racket] Username

From: Eli Barzilay (eli at barzilay.org)
Date: Wed Dec 7 10:43:11 EST 2011

9 hours ago, José Lopes wrote:
> Hello everyone,
> 
> How do I get the username of the person who is logged in the system?
> 
> At the moment I am doing this, but it looks terrible...
> 
> (define (current-user)
>    (path->string (file-name-from-path (find-system-path 'home-dir))))

It doesn't only look terrible, it's wrong since the home directory can
have any name.

An easy way to get it is to use the environment:

  (getenv "USER")

This is just the rough idea, it should really check that it's
defined.  On Windows you'll need the "USERNAME" variable instead.

Another easy way is to use the `whoami' command:

  (require racket/system racket/port)
  (regexp-replace #rx"\r?\n$"
                  (with-output-to-string (  () (system "whoami")))
                  "")

This is also just a rough idea, it should really also check that the
command succeeded and that the output is as expected.  On Windows
you'll need to get rid of the group name that you get from its whoami
command.

You can also go with an ffi -- for example:

  (require ffi/unsafe)
  (define geteuid  (get-ffi-obj 'geteuid #f (_fun -> _int)))
  (define getpwuid (get-ffi-obj 'getpwuid #f (_fun _int -> (_ptr o _string))))
  (getpwuid (geteuid))

But this is even more rough, it assumes that the return type is an
integer, doesn't check the result, abuses the fact that the returned
struct has a pointer to the username as its first field, and it's also
better to use getpwuid_r() to avoid the obvious problems. and probably
a bunch of other issues.  It might also break on platforms where some
of these assumptions are wrong.  On Windows you'll probably want to
use GetUserName().

(There could be other ways too -- like parsing the "/etc/passwd" file,
inspecting things in "/proc/self", etc...)

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                    http://barzilay.org/                   Maze is Life!



Posted on the users mailing list.