1

C standard library functions getenv and setenv can be used to access environment variables for a process.

In Linux, there is a documented global variable environ which holds environment variable value strings, so one could in principle use it directly and not use getenv and setenv.

My questions are:

  1. Why is environ exposed and documented to the application programmer, where it seems unnecessary to do so?

  2. Does any software now, or is future software likely, to use environ directly?

3
  • 1
    Guess: It's for compatibility reasons; the first unixes probably just used environ, because setenv and getenv didn't exist. And there may very well be some legacy programs which still do it that way.
    – dirkt
    Feb 7, 2017 at 8:44
  • This is a question for Linux kernel coders, more likely, and it is less likely to get a good answer here because it is broad and subject to personal opinion on the matter. Feb 8, 2017 at 23:01
  • It's not just Linux, it's POSIX. getenv is standard C, but environ main(,,envp) setenv unsetenv putenv are only POSIX and there are non-POSIX implementations of C. Feb 12, 2017 at 8:59

1 Answer 1

2
  1. To answer your second question first,
    • Trivially, the env and printenv programs use environ to list the entire environment.
    • Most shells use environ to copy each environment variable into an exported shell variable.  (For example, in bash, commands like set, export and declare (with no arguments) will list the entire environment, along with non-exported variables.)
    • I’m not sure exactly how they handle it, but su and sudo pass a sanitized copy of the environment to the programs they invoke.  They might do it by iterating through the environment and deciding which variables to pass through, which to omit, and which to modify.
  2. Why is environ exposed and documented to the application programmer?
    • Because some programs need it (see above).
    • The kernel has to pass the environment to the process (when it starts) somehow.  getenv and setenv (and a few other things) need to have access to the environment.  It’s tricky for the kernel to communicate to a library routine that isn’t active (i.e., to pass information to any part of the program other that the routine that is invoking the kernel).  It becomes doubly difficult given that, if you’re using static libraries, getenv and setenv won’t even be linked into your process image if the program doesn’t call them.  Using a global variable is the easiest solution.
    • Why did the designers/developers do it that way?  Why not?  The process owns its environment; it’s allowed to do whatever it want with it.
1
  • awk and perl also expose to scripts the entire set of envvars, as does Java to programs (though it recommends people use Java's properties scheme a la -Dname=value instead). Feb 12, 2017 at 9:12

Not the answer you're looking for? Browse other questions tagged .