linux之getenv putenv setenv和unsetenv详解

1、getenv函数

  头文件:#include<stdlib.h>

  函数原型: char * getenv(const char* name);

  函数说明:getenv()用来取得参数name环境变量的内容。

  函数参数:name为环境变量的名称,如果该变量存在则会返回指向该内容的指针。环境变量的格式为name=value。

  返回值:若环境变量存在,返回环境变量值的指针,否则返回NULL

  

  例子:

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 int main()
 4 {
 5     char* path = NULL;
 6     if((path = getenv("USER")))
 7         printf("USER = %s
", path);
 8 
 9     return 0;
10 }
View Code

  执行的结果是USER = hxinuan,其中hxinuan是我个人计算机的名字

 2、putenv函数

  头文件:#include<stdlib.h>

  函数原型: int putenv(const char* str);

  函数说明:putenv用来改变或者增加环境变量的内容

  参数:str的格式为name=value,若环境原先存在,则环境变量值会依参数str改变,若不存在,则增加该环境变量

  返回值:成功返回0,错误返回-1.

  

  例子:

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 int main()
 4 {
 5     char* path = NULL;
 6     if((path = getenv("USER")))
 7         printf("USER = %s
", path);
 8 
 9     putenv("USER=test");
10 
11     if((path = getenv("USER")))
12         printf("USER = %s
", path);
13     return 0;
14 }
View Code

   执行的结果为:

  USER = hxinuan

  USER = test

  改变的环境的变量只在程序中有效,你在程序里做的改变不会反映到外部环境中,这是因为变量的值不会从子进程传播到父进程,这样做更安全。

3、setenv函数

  头文件:#include<stdlib.h>

  函数原型: int setenv(const char* name, const char* value, int overwrite)

  函数说明:setenv用来改变或者增加环境变量

  参数:name为环境变量名称字符串。 value则为变量内容,overwrite用来决定是否要改变已存在的环境变量。如果overwrite不为0,而该环境变量原已有内容,则原内容会被改为参数value所指的变量内容。如果overwrite为0,且该环境变量已有内容,则参数value会被忽略。

  返回值:成功返回0,错误返回-1.

  

  例子:

   

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 int main()
 4 {
 5     char* path = NULL;
 6     if((path = getenv("USER")))
 7         printf("USER = %s
", path);
 8 
 9     setenv("USER", "test", 1);
10 
11     if((path = getenv("USER")))
12         printf("USER = %s
", path);
13     return 0;
14 }
View Code

  执行的结果仍为:

  USER = hxinuan

  USER = test

  通过setenv函数设置的环境变量只在本进程,而且是本次执行中有效。如果在某一次运行程序时执行了setenv函数,进程终止后再次运行该程序,上次的设置是无效的,上次设置的环境变量是不能读到的。

4、unsetenv函数

  头文件:#include<stdlib.h>

  函数原型: int unsetenv(const char* name)

  函数说明:删除name环境变量的定义,即使不存在也不会出错

  参数:name为环境变量名称字符串。 

  返回值:成功返回0,错误返回-1.

  

  例子:

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 int main()
 4 {
 5     char* path = NULL;
 6     unsetenv("USER");
 7     path = getenv("USER");
 8     printf("USER = %s
", path);
 9 
10     return 0;
11 }
View Code

   执行的结果:

  USER = (null)

原文地址:https://www.cnblogs.com/Hxinguan/p/5010121.html