linux 环境变量

本文介绍如何使用C语言的putenv和getenv函数访问和设置环境变量,包括通过命令行参数获取环境变量值及在程序中设置新环境变量的方法。此外,解释了在程序内部设置的环境变量不会影响到外部环境的原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

env命令列出所有环境变量

env

输出:

HOME=/home/yaoyin
LOGNAME=yaoyin
......

 

c语言程序可以通过putenv和getenv访问环境变量

#include <stdlib.h>

char *getenv(const char * name);

int putenv(const char *string);

代码:environ.c文件

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc,char*argv[])
{
  char *var, *value;
  if(1==argc || argc > 3)
        {
         fprintf(stderr,"\n");
         exit(1);
        }
 var = argv[1];
 value=getenv(var);
 if(value)
        printf("%s",value);
 else
        printf("none value\n");
 if(3==argc)
 {
  char *string;
  value = argv[2];
  string = malloc(strlen(var)+strlen(value)+2);
  strcpy(string,var);

strcat(string,"=");

strcat(string,value);
putenv(string);
  value=getenv(var);
  printf("%s",value);}

}

gcc environ.c -t test

./test HOME

./test YourName YaoYin

注意:YourName is local only to the environ.c.在程序中的变化不会反映到外部环境中,这是因为变量的值没有从子进程

(environ.c)传播到父进程(shell)

 

the environ variable:

#include <stdlib.h>

extern char **environ;

代码:showenv.c

#include <stdlib.h>
#include <stdio.h>
extern char ** environ;
int main()
{
char **env = environ;
while(*env)
{
printf("%s\n",*env);
env++;
}
exit(0);
}

gcc showenv.c -o test

./test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值