c++environment-variablesstdstandards

In the C++ standard why is getenv defined but not setenv?


Can't seem to find the definition of setenv or something similar in the standard.

whereas getenv seems to be there and is available portably in both windows and posix standard libraries.

In short is there a reason or discussion as to why this might be?


Solution

  • getenv() is useful

    You can use it to get environmental data as input to your program. This is the primary purpose of the shell’s environment table — provide a way for the user to modify the behavior of system programs.

    For example, on Linux, the $LS_COLORS environment variable is a way to modify the colors used to display directory information using the ls (list directory) program. Every user can set his or her own preferred color scheme to use when displaying a file listing with ls, even though ls is a system program.

    putenv() is not useful (generally)

    A program may modify its environment table, but it cannot modify the environment table of other programs, such as the parent shell! This is by design, and is a security feature.

    Both *nixen and Windows have functions that do allow you to add or modify variables in the current process’s environment table. This is useful when spawning a child process, which can be explicitly initialized to inherit the current process’s environment table. But such behavior is largely a specialized need, so there is no good argument to make such a function part of the C Standard.

    It used to be possible to sneakily modify other processes’ environment tables on Windows, assuming you had sufficient permissions to do so, but such behavior has been made much more difficult since XP or so.