Processes 127
and there is no variable (corresponding to argc) that specifies the size of the envi-
ronment list. (For similar reasons, we don’t number the elements of the environ
array in Figure 6-5.)
Listing 6-3: Displaying the process environment
––––––––––––––––––––––––––––––––––––––––––––––––––––––––proc/display_env.c
#include "tlpi_hdr.h"
extern char **environ;
int
main(int argc, char *argv[])
{
char **ep;
for (ep = environ; ep != NULL; ep++)
puts(ep);
exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––––––––proc/display_env.c
An alternative method of accessing the environment list is to declare a third argu-
ment to the main() function:
int main(int argc, char *argv[], char *envp[])
This argument can then be treated in the same way as environ, with the difference
that its scope is local to main(). Although this feature is widely implemented on
UNIX systems, its use should be avoided since, in addition to the scope limitation,
it is not specified in SUSv3.
The getenv() function retrieves individual values from the process environment.
Given the name of an environment variable, getenv() returns a pointer to the corre-
sponding value string. Thus, in the case of our example environment shown ear-
lier, /bin/bash would be returned if SHELL was specified as the name argument. If no
environment variable with the specified name exists, then getenv() returns NULL.
Note the following portability considerations when using getenv():
z SUSv3 stipulates that an application should not modify the string returned by
getenv(). This is because (in most implementations) this string is actually part of
the environment (i.e., the value part of the name=value string). If we need to
change the value of an environment variable, then we can use the setenv() or
putenv() functions (described below).
#include <stdlib.h>
char *getenv(const char *name);
Returns pointer to (value) string, or NULL if no such variable