博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux 环境变量函数getenv()和putenv()的使用
阅读量:6954 次
发布时间:2019-06-27

本文共 2138 字,大约阅读时间需要 7 分钟。

环境变量相关函数:

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 
#include
#include
/************************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)

 

转载于:https://www.cnblogs.com/PHL666/p/10747312.html

你可能感兴趣的文章
VirtualBox是什么
查看>>
linux定时任务Crond之服务器同步时间05
查看>>
需求改进与系统设计
查看>>
jquery特效 商品SKU属性规格选择实时联动
查看>>
HashMap[转]
查看>>
面向对象程序设计——总结作业
查看>>
linux之 sed命令
查看>>
oracle rac的特征
查看>>
Linux之 find之 ctime,atime,mtime
查看>>
mysql查询
查看>>
Mongodb JAVA API
查看>>
MacFree ePlicy Orchestrator
查看>>
python基础之列表生成式和生成器
查看>>
关于java.lang.ClassNotFoundException
查看>>
转换成CSV文件、Word、Excel、PDF等的方法--读取CSV文件的方法
查看>>
一条SQL语句查询出成绩名次 排名 (转)
查看>>
什么是.NET应用程序域
查看>>
ZooKeeper 安装与部署
查看>>
Picnic Planning
查看>>
文章标题
查看>>