Linux/Unix 系统编程手册 上册
每一个进程都有与其相关的称之为环境列表的字符串数组(环境),每个字符串都以名称=值形式定义。环境是”名称-值“的成对集合,可存储任何信息。
新进程在创建之时,会继承其父进程的环境副本,这是一种原始的进程间通信方式,环境提供了将信息从父进程传递给子进程的方法。由于子进程只有在创建时才能获得其父进程的环境副本,所以这一信息传递是单向的、一次性的。子进程创建后,父、子进程均可更改各自的环境变量,且这些变更对对方而言不再可见。
环境变量的常见用途之一是在 shell 中,通过自身环境中放置变量值,shell 就可确保把这些值传递给其所创建的进程,并以此来执行用户命令。
查看环境变量
1、/proc/PID/environ
2、全局变量 char** environ
extern char** environ;
setenv()
int setenv(const char* name, const char* value, int overwrite);
-
overwrite != 0
修改 value 为指定值; -
overwrite == 0
忽略指定的 value 值;
增加或修改变量,可以为变量设置初始值。
setenv("BYE", "byebye", 0)
putenv()
增加或修改变量。
./a.out BYE=byebye
+ putenv("BYE")
操作环境变量
q@ubuntu:~$ cat test.c
#include <stdlib.h>
#define _GNU_SOURCE
extern char** environ;
int main(int argc, char* argv[])
{
int j;
char** ep;
clearenv();
for(j = 1; j < argc; j++)
{
if(putenv(argv[j]) != 0)
return -1;
}
if(setenv("GREET", "hello world", 0) == -1)
return -1;
unsetenv("BYE");
for(ep = environ; *ep != NULL; ep++)
puts(*ep);
return 0;
}
q@ubuntu:~$ ./a.out "GREET=Guten Tag" SHLL=/bin/bash BYE=Ciao
GREET=Guten Tag
SHLL=/bin/bash
q@ubuntu:~$ ./a.out SHELL=/bin/sh BYE=byebye
SHELL=/bin/sh
GREET=hello world
q@ubuntu:~$ ./a.out
GREET=hello world