【linux草鞋应用编程系列】

一、 环境变量

应用程序在执行的时候,可能需要获取系统的环境变量,从而执行一些相应的操作。

在linux中有两种方法获取环境变量,分述如下。

1、通过main函数的参数获取环境变量

main函数的多种定义方式:

int main(void);int main(int argc, char* argv[ ]);int main(int argc, char* argv[ ], char* env[ ] )

View Code

方式1和方式2比较常见,下面介绍一下方式3: 第三个参数获取系统的环境变量。

Exp:

#include <stdio.h>int main(int argc,char* argv[], char* env[]){int i=0;while(env[i]){puts(env[i++]);}return 0;}

程序执行的时候就可以输出所有的环境变量。

2、访问全局变量 environ 获取环境变量

在加载应用程序的时候,linux系统会为每一个应用程序复制一份系统环境变量副本,保存在全局变量 enviro 中。

可以通过这个全局的变量访问系统的环境变量。

Exp:

#include <stdio.h>extern char** environ;int main(int argc,char* argv[]){int i=0;while(environ[i]){puts(environ[i++]);}return 0;}

3、获取指定的环境变量

linux提供环境变量操作相关的函数: getenv( )、putenv( )、setenv()、unsetenv()、clearenv( ).

getenv( )

GETENV(3)Linux Programmer’s ManualGETENV(3)NAMEgetenv – get an environment variableSYNOPSIS#include <stdlib.h>

返回值:

成功返回指向环境变量的值的指针,失败返回NULL。

putenv( )

UTENV(3)Linux Programmer’s ManualPUTENV(3)NAMEputenv – change or add an environment variable //增加或者改变环境变量的值SYNOPSIS#include <stdlib.h>int putenv(char *string); //设置的环境变量字符串, string的格式如下: HOME=/home/volcanol

setenv( ) 和 unsetenv()

SETENV(3)Linux Programmer’s ManualSETENV(3)NAMEsetenv – change or add an environment variable //改变或者增加环境变量SYNOPSIS#include <stdlib.h>*value, overwrite);unsetenv(

DESCRIPTIONThe setenv() function adds the variable name to the environment with the valuevalue, if name does not already exist. If name does exist in the environment, thenits value is changed to value if overwrite is non-zero; if overwrite is zero, thenthe value of name is not changed.The unsetenv() function deletes the variable name from the environment.

注意:

unsetenv 会将环境变量删除,包括环境变量的名和环境变量的值

clearenv()清除所有的环境变量,并设置environ 的值为NULL。

CLEARENV(3)CLEARENV(3)NAMEclearenv – clear the environmentSYNOPSIS#include <stdlib.h>int clearenv(void);DESCRIPTIONThe clearenv() function clears the environment of all name-value pairs and sets thevalue of the external variable environ to NULL.

  注意这个地方: 没有 linux program manual 的字样,表示这个函数需要慎重使用。

Exp: getenv( ) 和 setenv( )

#include <stdio.h>#include <stdlib.h>int main(int argc,char* argv[]){char* env;setenv(,, 1);env=getenv();printf(,env);return 0;}

执行结果如下:

[root@localhost process]# gcc main.c [root@localhost process]# ./a.out the Test-env is: this is a test env

要点:

这样设置的环境变量仅对当前进程有效,其他进程是无效的。

回避现实的人,未来将更不理想。

【linux草鞋应用编程系列】

相关文章:

你感兴趣的文章:

标签云: