开发者

List environment variables with C in UNIX

Is there a way to enumerate environment variables and retrieve values using 开发者_StackOverflow社区C?


Take a look at the environ global variable.

extern char **environ;

It might be defined in unistd.h (take a look at the environ (5) man page above).

Here's a little code demo I wrote:

#include <stdio.h>
extern char **environ;

int main()
{
    for (char **env = environ; *env; ++env)
        printf("%s\n", *env);
}

Here's how to use it:

matt@stanley:~/Desktop$ make enumenv CFLAGS=-std=c99
cc -std=c99    enumenv.c   -o enumenv
matt@stanley:~/Desktop$ ./enumenv 
ORBIT_SOCKETDIR=/tmp/orbit-matt
SSH_AGENT_PID=1474
TERM=xterm
SHELL=/bin/bash
... (so forth)


The environment information can be passed as an extra parameter to main. I don't know if it is compliant or not, but it definitely works (tested on Ubuntu). Just define the extra argument and its an array of char pointers terminated by a NULL pointer. The following will print out the lot.

#include <stdio>

int main(int argc, char *argv[], char *envp[])
{
  int index = 0;
  while (envp[index])
    printf("%s\n", envp[index++];
}


There is a demo in the book "The Linux Programming Interface" at page 127.

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜