linux 环境变量函数getenv()和putenv()的使用

环境变量相关函数:

getenv()和putenv()

代码示例【Linux程序设计(4th)_4.2小节配套代码】:

程序功能:编写一个程序来打印所选的任意环境变量的值;如果给程序传递第二个参数,还设置环境变量的值
//
1 The first few lines after the declaration of main ensure that the program, environ.c, has been called correctly. #include <stdlib.h> #include <stdio.h> #include <string.h> /************************ argc:参数个数(包含程序名) argv:代表参数自身的字符串数组; argv[0]为程序名,argv[1]为第1个实际参数 argv[2]为第2个实际参数 ************************/ int main(int argc, char *argv[]) { char *var, *value; if(argc == 1 || argc > 3) { //确保实际参数只有1个(argc=2)或2个(argc=3) fprintf(stderr,"usage: environ var [value]\n"); exit(1); } // 2 That done, we fetch the value of the variable from the environment, using getenv. var = argv[1]; //第一个实际参数的参数名 value = getenv(var); //第一个实际参数的参数值 if(value) //判断参数值是否存在 printf("Variable %s has value %s\n", var, value); else printf("Variable %s has no value\n", var); // 3 Next, we check whether the program was called with a second argument. If it was, we set the variable to the value of that argument by constructing a string of the form name=value and then calling putenv. if(argc == 3) { //如果第二个实际参数存在 char *string; value = argv[2]; //获取第2个参数的值 string = malloc(strlen(var)+strlen(value)+2); //为第二个参数的“参数名=参数值”开辟空间(+2表示“=”和空格) if(!string) { //如果开辟空间失败 fprintf(stderr,"out of memory\n"); exit(1); } strcpy(string,var); strcat(string,"="); strcat(string,value); printf("Calling putenv with: %s\n",string); if(putenv(string) != 0) { //putenv()成功返回0.若环境变量设置失败 fprintf(stderr,"putenv failed\n"); free(string); //释放开辟的内存空间 exit(1); } // 4 Finally, we discover the new value of the variable by calling getenv once again. value = getenv(var); if(value) printf("New value of %s is %s\n", var, value); else printf("New value of %s is null??\n", var); } exit(0); }

 注意:环境仅对程序本身有效。在程序里做的环境变量更改不会反映到外部环境,这是因为变量的值不会从子进程(你的程序)传播到父进程(shell)

 

猜你喜欢

转载自www.cnblogs.com/PHL666/p/10747312.html
今日推荐