Add Book to My BookshelfPurchase This Book Online

Chapter 16 - Miscellaneous Routines

UNIX Systems Programming for SVR4
David A. Curry
 Copyright © 1996 O'Reilly & Associates, Inc.

Environment Variables
Each process has a set of associated variables. The variables are called environment variables and, together, constitute the process environment. These variables include the search path, the terminal type, and the user's login name. The UNIX shells provide a method for adding, changing, and removing environment variables.
As discussed in Chapter 11, Processes, a program is started by a call to main:
    int
    main(int argv, char **argv, char **envp)
The argc and argv parameters are the number of arguments passed to the program and the arguments themselves. The envp parameter is the array of environment variables. The execve and execle functions described in Chapter 11 can be used to execute a program with a new set of environment variables; the other exec functions allow the program to inherit its environment from the parent. Example 16-7 shows a small program that prints its environment variables.
Example 16-7:  printenv
#include <stdio.h>
int
main(int argc, char **argv, char **envp)
{
    while (*envp != NULL)
        printf("%s\n", *envp++);
    exit(0);
}
    % printenv
    HOME=/home/foo
    HZ=100
    LOGNAME=foo
    MAIL=/var/mail/foo
    PATH=/usr/opt/bin:/usr/local/bin:/usr/bin
    SHELL=/bin/sh
    TERM=xterm
    TZ=US/East-Indiana
To obtain the value of a specific environment variable, the getenv function is used:
    #include <stdlib.h>
    char *getenv(char *name);
The name parameter should be the name of the desired variable (the name to the left of the '=' in the example above). If the variable exists, its value (to the right of the '=') is returned; otherwise, NULL is returned.
Most newer versions of UNIX, SVR4 included, also provide the putenv function, which places a new variable into the environment:
    #include <stdlib.h>
    int putenv(char *string);
The putenv function uses malloc to allocate a new environment large enough for the old environment plus the string contained in string. The string contained in string should be of the form name=value; by convention, environment variable names are usually all uppercase. Note that the string variable should remain in existence for the life of the program; that is, it should be declared static or dyanmically allocated. Changing the value of string will change the value of the variable in the environment.
If the environment is successfully modified, putenv returns 0; otherwise it returns non-zero.

Previous SectionNext Section
Books24x7.com, Inc © 2000 –  Feedback