2

Is there any namespace (process, user, etc) that isolates environment variables?

In case there is, what happens when you unshare? Do they get cloned? What happens if a process changes an existing variable?

EDIT: I am using Ubuntu

Kusalananda
  • 333,661

2 Answers2

4

You don't need any namespace to isolate environment variables. They're already isolated and private to each process. Modifying an environment variable in a child process will NOT propagate to its parent.

Environment variables in Unix are just a bunch of strings stored in the address space of a process. When a process forks, its children will "inherit" a copy of them together with the whole address space, and when a program executes another (and replaces the entire content of the address space), they have to be passed explicitly as the envp argument to the execve(2) system call if they're to be preserved.

If you want to start a process with an empty environment, you can start it as

env - cmd ...

which will just call execve("/path/to/cmd", ["cmd", ..., NULL], [NULL]).

Or to run it with an environment containing just FOO=bar:

env - FOO=bar cmd ...

Both the namespace affecting system calls (clone(2), unshare(2), setns(2)) and command line utilities like unshare(1) do not consider or affect the environment in any special way.


Note: This is how it works in Unix, not some law of nature. On other systems like plan9 (where the concept the namespace originated, but where all namespaces are basically mount namespaces, since everything there is a file/system) the environment is just a filesystem mounted by default on /env and, contrary to Unix, shared by default between the parent and the child.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • Is this the same in Linux? Every time I start a process all that data is copied to the process memory? Thanks! – Carlos Garcia Apr 01 '20 at 07:11
  • I think I got it now, the initial variables, which i believed they were "global" (like in windows) they are actually not, and they are just written in some file. Thank you for your answer! – Carlos Garcia Apr 01 '20 at 07:44
  • For all intents and purposes, Linux is Unix. 2. Yes all that data is copied, see here for some low level details. You may think of the environment strings as of "hidden" command line arguments -- which are automatically added to each command for your convenience.
  • –  Apr 01 '20 at 14:33