linux删除环境变量后getenv,linux 环境变量函数getenv()和putenv()的使用

本文介绍了如何在C语言中使用getenv()和putenv()函数来读取和设置环境变量。程序首先检查命令行参数,然后通过getenv()获取指定变量的值,并在存在第二个参数时使用putenv()设置新的环境变量值。请注意,环境变量的更改只在当前进程中有效,不会影响父进程。
摘要由CSDN通过智能技术生成

环境变量相关函数:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值