简体   繁体   English

如何获取C程序本身设置的所有环境变量?

[英]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. 我正在编写一个使用system()函数设置环境变量的C程序。

Is there any collection which can give me the environment variables which were set by C program? 是否有任何集合可以为我提供由C程序设置的环境变量? I need to use the collection in the C program. 我需要在C程序中使用集合。

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). 在Linux和类似系统中,当您运行一个进程(例如执行C程序)时,该进程是创建它的进程的子进程 (通常是命令行shell或桌面/ GUI管理器)。 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 . 子进程可以使用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). 如果子进程使用system或其他例程创建自己的子进程,则在该“孙”进程中创建的任何环境变量都不会影响其父进程(我们的第一个子进程)。

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 . 程序可以创建自己的子进程,并指定要在子进程中创建的环境变量,例如execle等各种exec*例程。
  • 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. 该程序将环境变量的设置写入stdout或另一个流,然后协作过程读取这些设置并相应地设置其自己的环境变量。 An example of this is using the command eval `ssh-agent -s` in a Bourne-type shell. 一个示例是在Bourne类型的shell中使用命令eval `ssh-agent -s` 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. 该命令告诉外壳程序执行命令ssh-agent -s ,然后像评估命令一样评估该命令的输出。

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: 据我所知,没有标准化的方法可以访问所有环境变量,但是几乎所有系统都支持使用第三个参数声明一个main函数,该函数将接收一个以NULL终止的字符串数组,这些字符串反映了整个环境:

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. 那应该打印所有环境变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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