[Gllug] cuserid?
Peter Grandi
pg_gllug at gllug.for.sabi.co.UK
Mon Oct 17 14:21:54 UTC 2005
>>> On Mon, 17 Oct 2005 15:10:16 +0100, Peter Childs
>>> <peterachilds at gmail.com> said:
peterachilds> How do I find out who the current user is as
peterachilds> returned by whoami in c I've been using cuserid
peterachilds> but I've just hit a problem that some of the
peterachilds> username are more than 9 characters in length. All
peterachilds> the docs seam to surgest using the environment
peterachilds> varable LOGNAME but this does not seam to be right
peterachilds> either. Any ideas
Well in the general case this is impossible; what a process
really knows is the current numeric id (actually one of two at
least), not the user name, as that may be missing or ambiguous.
The main problem is that several user names may have the same
numeric user id, there may be no name for that user numeric user
id, and which one was used to log in (if a login occurred) may
be not available.
Now, SysV 'login'/'getty' sets '$LOGNAME', the traditional
version sets '$USER', but this is not guaranteed (e.g. if the
process is not descended from a login)' also it is not
guaranteed that any of these will not have been modified in
between. 'whoami' in particular looks at '/var/log/wtmp' IIRC.
The best bet is severalfold: check both '$USER' and '$LOGNAME'
first, then if that fails find out which one is the current tty,
and use 'wtmp'(5) to get the login name if any, then decide
whether you want to the normal or effective numeric user id, and
then use 'getpwuid'(3) to resolve that to a string name.
As a shortcut you can look at the output of 'id -a' for example.
BTW, this is a bit of an advanced UNIX programming question, as
there are tutorials/books on UNIX user name/id issues that
perhaps you should consider reading, as the subject is really
not as simple as «who the current user is as returned by
whoami», for example the Stevens book on advanced UNIX
programming (IIRC).
--
Gllug mailing list - Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug
More information about the GLLUG
mailing list