I have a parent process running as 'root' user. After fork()
, execl()
and setuid()/setgid()
, the child process is started as another OS user (say user1).
Printing the environment shows that this is same as the root environment (as if logging in as root) and not as if logging in as user1. Why?
Is there a way to read the environment of user1 in the child process?
Best Answer
Each process has its own environment, copied from the parent. If the parent is a shell, there's a concept of exportable variables which needs to be considered, but this does not apply when you are dealing with
exec()
etc directly. TheLOGNAME
variable is typically set by a login shell, you're just seeing a leftover value that was not reset. So, you are seeing the child environment. On some systems you cannot easily access the parent (or other process) environment, on Linux you can do this easily (subject to permissions) via/proc
)You can probably reproduce the effect you are seeing by trying both
su
andsu -
, the latter will initialize a shell login environment which will (almost certainly) resetLOGNAME
amongst other things, the former will leave it untouched.Using the
env
command is one way of getting a clean environment when starting a new process from a command line, you should check theexecle()
documentation on your system to see how to do something similar.