简体   繁体   中英

How to get all environment variables set by a C program itself?

I am writing a C program that sets environment variables using system() function.

Is there any collection which can give me the environment variables which were set by C program? I need to use the collection in the C program.

In Linux, and similar systems, when you run a process (such as executing a C program), the process is a child process of the process that creates it (usually a command-line shell or a desktop/GUI manager). The creating process is the parent process . Any “environment variables” set in the child process do not affect the parent process.

The child process can examine its own environment variables with getenv .

If the child process creates its own child process, with system or another routine, any environment variables created in that “grandchild” process will not affect its parent (our first child process).

Two common ways for a program to provide environment variables for another process to use are:

  • The program may create its own child process and specify environment variables to be created in the child process, as with the various exec* routines such as execle .
  • The program writes settings for environment variables to stdout or another stream, and a cooperating process reads those settings and sets its own environment variables accordingly. An example of this is using the command eval `ssh-agent -s` in a Bourne-type shell. This command tells the shell to execute the command ssh-agent -s and then to evaluate the output of that command as if it were commands.

There is no standardized way to access all environment variables to my knowledge, but almost all systems support declaring a main function with a third argument, which will then receive a NULL-terminated array of strings which reflect the entirety of the environment:

int main(int argc, char **argv, char **envp)
{
    char **p;

    for(p = envp; *p != NULL; p++)
        printf("%s\n", *p);
    return(0);
}

That should print all environment variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM