Is there a way to enumerate environment variables and retrieve values using C?
3 Answers
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) 7 Comments
extern char **environ; if you want to use it.unistd.h if __USE_GNU is set, which indicates it's an extension. (FWIW, __environ, also an extension, is declared unconditionally).<unistd.h> has taken the sensible step of requiring it. It was the only variable without a declaration in a system header. The only oddball left that I know of is union semun.semun thing. scary.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++]; } 4 Comments
extern char **environ;.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); }