Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

212 Process Environment Chapter 7


FreeBSD Linux Mac OS X Solaris
Function ISO C POSIX.1 8.0 3.2.0 10.6.8 10

getenv •• ••• •
putenv XSI • •• •
setenv ••••
unsetenv ••••
clearenv •

Figure 7.8 Support for various environment list functions

Theclearenvfunction is not part of the Single UNIX Specification. It is used to remove all
entries from the environment list.

The prototypes for the middle three functions listed in Figure7.8 are
#include <stdlib.h>
int putenv(char *str);
Returns: 0 if OK, nonzero on error
int setenv(const char *name,const char *value,intrewrite);
int unsetenv(const char *name);
Both return: 0 if OK,−1 on error
The operation of these three functions is as follows:

•Theputenvfunction takes a string of the formname=valueand places it in the
environment list. Ifnamealready exists, its old definition is first removed.
•The setenv function sets name to value.If name already exists in the
environment, then (a) ifrewriteis nonzero, the existing definition fornameis first
removed; or (b) ifrewriteis 0, an existing definition fornameis not removed,
nameis not set to the newvalue,and no error occurs.
•Theunsetenvfunction removes any definition ofname.It is not an error if
such a definition does not exist.

Note the difference betweenputenvandsetenv.Whereassetenvmust allocate memory to
create thename=valuestring from its arguments,putenvis free to place the string passed to it
directly into the environment. Indeed, many implementations do exactly this, so it would be
an error to passputenvastring allocated on the stack, since the memory would be reused
after we return from the current function.

It is interesting to examine how these functions must operate when modifying the
environment list. Recall Figure7.6: the environment list—the array of pointers to the
actualname=valuestrings — and the environment strings aretypically stored at the top
of a process’s memory space, above the stack. Deleting a string is simple; we just find
the pointer in the environment list and move all subsequent pointers down one. But
adding a string or modifying an existing string is moredifficult. The space at the top of
the stack cannot be expanded, because it is often at the top of the address space of the
Free download pdf