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