加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-14 01:33:04 所属栏目:Linux 来源:网络整理
导读:环境变量相关函数: getenv()和putenv() 代码示例【Linux程序设计(4th)_4.2小节配套代码】: 程序功能:编写一个程序来打印所选的任意环境变量的值;如果给程序传递第二个参数,还设置环境变量的值 // 1 The first few lines after the declaration of main
环境变量相关函数:

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 %sn",var,value); else printf("Variable %s has no valuen",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 memoryn"); exit(1); } strcpy(string,var); strcat(string,"="); strcat(string,value); printf("Calling putenv with: %sn",string); if(putenv(string) != 0) { //putenv()成功返回0.若环境变量设置失败 fprintf(stderr,"putenv failedn"); 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 %sn",value); else printf("New value of %s is null??n",var); } exit(0); }

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读