Name: _____________________ Class: CET 421
SSN/ID:   _____________________ Section & Group: ____________
Reference: Environment Access Functions


 

Each process has an environment associated with it. The environment strings are usually of the form:

name=value (standard NULL terminated strings)

and are referenced by an array of pointers to these strings. This array is made available to a process through the C Run Time library as:

extern char **environ; // NULL terminated array of char *

While an application can access the environment directly through this array, some functions are available to access and manipulate the environment:

#include <stdlib>

char *getenv(const char *name);

Returns pointer to value associated with name, NULL if not found.

getenv returns a pointer to the value of a name=value string. You should always use getenv to fetch a specific value from the environment rather than accessing environ directly.

getenv is supported by both the ANSI C and POSIX standards,

In addition to fetching the value of an environment variable, sometimes it is necessary to set a variable. You mjay want to change the value of an existing variable, or add a new variable to the environment. Unfortunately not all systems support this capability.

#include <stdlib>

int putenv(const char *str);

int setenv(const char *name, const char *value, int rewrite);

Both return: 0 if OK, non-zero on error

void unsetenv(const char *name);

You may need to use putenv with the environment value left blank to unset an environmment object. i.e. putenv("myname=")

The descriptions of the system functions above are drawn from sources that include manuals on the Sun Solaris system and the MAC OS X Darwin/BDS system, and also from 'Advanced Programming in the UNIX Environment', W. Richard Stevens, Addison-Wesley, 1993.

 


Ricky J. Sethi <rickys at sethi.org>
Last modified: Mon Jun 6 01:07:35 PDT 2005