How do I get the users real uid if the program is run with sudo?

c, ubuntu

Solution

`sudo` provides some environment variables to help you with exactly this case:

   SUDO_UID        Set to the user ID of the user who invoked
                   sudo

   SUDO_USER       Set to the login of the user who invoked sudo

steveayre has pointed out in the comments that the user can set these environment variables in some cases; the `sudo(8)` manpage includes in part:

The sudoers policy subjects variables
passed on the command line to the same restrictions as normal
environment variables with one important exception.  If the
setenv option is set in sudoers, the command to be run has the
SETENV tag set or the command matched is ALL, the user may set
variables that would otherwise be forbidden.  See sudoers(5)
for more information.

So be sure that you don't grant `ALL` commands to users when you need to rely upon this feature.

Problem

The program I am running needs root privledges and therefore is run with `sudo`, but it also needs to know what user is running it. `getuid` and `geteuid` both return `root`. How do I get the actual users username (or uid)? Thanks!

Original source