随笔-159  评论-114  文章-7  trackbacks-0

环境变量,在程序中获取。

shell命令,env 命令 (whereis ps which ps)

env|grep JAVA

程序中获取环境变量

#include <iostream>
using namespace std;

int main(int argc,char** argv, char** env)
{
        
while(env&&*env){
                cout 
<< *env << endl;
                
++env;
        }

        
return 0;
}


c++,一个字符串数组,以char**的指针代表的。

Untitled-1.gif
所以遍历时,既要判断env指向的指针数组是否为空,也要判断*env是不是到末端。

=======================================

Unix 系统调用函数,getenv。

man getenv (或者man -k getenv    man -a getenv)

SYNOPSIS
     #include <stdlib.h>

     char *getenv(const char *name);

得到函数原型和需要包含的头文件。

RETURN VALUES
     If successful, getenv() returns a pointer to  the  value  in
     the  current  environment;  otherwise,  it  returns  a  null
     pointer.

#include <stdlib.h>
#include 
<iostream>

using namespace std;

int main()
{
        
char javahome[200];
        strcpy(javahome,getenv(
"JAVA_HOME"));
        cout 
<< javahome << endl;
        
return 0;
}

int putenv(const char* str); 成功返回0;

在程序中添加和修改的环境变量只对本进程起作用。

Untitled2.gif
代码栈,存储着函数调用的入口地址,通过pstack命令可以查看相应函数调用关系,也就是代码栈。

openlab.tarena.ca% pstack 3212
3212:   ljlserver
 ff198958 accept   (0, ffbefad8, ffbefad4, 1)
 00010e74 main     (1, ffbefb84, ffbefb8c, 216c4, 0, 0) + 348
 000109f4 _start   (0, 0, 0, 0, 0, 0) + 5c

Unix每个进程的启动都回调用_start,然后向main传入参数,在main调用前,env环境变量就已经拷贝到进程空间中了。_start负责提供前提条件。



posted on 2006-02-05 21:41 北国狼人的BloG 阅读(387) 评论(0)  编辑  收藏 所属分类: 达内学习总结

只有注册用户登录后才能发表评论。


网站导航: