LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 808|回复: 3

帮我看一下putenv

[复制链接]
发表于 2006-2-24 19:53:07 | 显示全部楼层 |阅读模式
#include <stdlib.h>
#include <stdio.h>
int main()
{
        static char envbuf[256];
       
        sprintf(envbuf,"MYVAR=%s","MYVAL");
       
        if(putenv(envbuf))
        {
                printf("Sorry, putenv() couldn't find the memory for %s\n",envbuf);
                /* Might exit() or something here if you can't live without it */
        }
        exit (0);
}
运行后  env |grep MYVAR  ,却没有显示结果,为什么?
发表于 2006-2-25 07:41:21 | 显示全部楼层
你写的没有错。只是你忽略了一点。当你在ternimal下运行一个程式时,这个程式复制了所有当前这个ternimal的环境变量。然后这个程式就成了一个单独的个体。当你要改变这个程式的环境变量,这些环境变量并不会影响到那个terninal。 我不到我解释的是不是很清楚。我改了你的程式,运行一下就知道为什么了。

#include <stdlib.h>
#include <stdio.h>


int main() {
        static char envbuf[256];
        char readenv[100];

        sprintf(envbuf,"MYVAR=%s","MYVAL");
       
        if(putenv(envbuf)) {
                printf("Sorry, putenv() couldn't find the memory for %s\n",envbuf);
                /* Might exit() or something here if you can't live without it */
        }


        strcpy(readenv, getenv("MYVAR"));
        printf("readenv: %s\n", readenv);


        exit (0);
}
回复 支持 反对

使用道具 举报

发表于 2006-2-25 11:29:41 | 显示全部楼层
那么子进程能否改变父进程的环境变量?

是否出于安全的考虑而无法实现?
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-2-26 08:51:37 | 显示全部楼层
运行你的程序看到了结果, 但是不明白,此程序中的对环境变量的修改将对那些进程,或者系统其他的什么,造成影响?
是不是此程序中的对环境变量的修改只对本进程造成影响?
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表