环境

环境是每个程序都可以存取的一个字符串数组,每个字符串都以var=value的形式出现。

在shell中列出环境:

$ env
ORBIT_SOCKETDIR=/tmp/orbit-orisun
WEKA_HOME=/home/orisun/develop/weka-3-7-4
SSH_AGENT_PID=1587
TERM=xterm
SHELL=/bin/bash

env是一个普通的程序,它并不是shell内置命令。

在shell中更新环境:

$ export var=value

在C语言中使用getenv()读入并修改环境:

#include<stdio.h>
#include<string.h>
#include<stdlib.h> //for getenv()
main(){
char *cp=getenv("LANG"); //获取环境
if(cp!=NULL && strcmp(cp,"fr")==0) //更改环境
printf("Bonjour\n");
else
printf("Hello\n");
}

exec之前子进程和父进程共享代码段。exec使代码段发生了复制,清除原来进程的所有代码和数据,插入新程序的代码和数据,但是环境从旧的进程被复制到了新的进程。

从environ变量中读取并修改环境:

#include<stdio.h>
#include<string.h>
#include<stdlib.h> //for getenv()
#include<unistd.h>
extern char **environ;
main(){
int i;
for(i=0;environ[i];i++) //读取环境
printf("%s\n",environ[i]);

char *table[3];
table[0]="TERM=vt";
table[1]="SHELL=/bin/bash";
table[2]=0; //环境数组的结尾

environ=table; //更改环境

execlp("env","env",NULL); //执行exec看看环境改变没有
}
posted @ 2011-12-24 11:47  张朝阳  阅读(317)  评论(0编辑  收藏  举报