guojinshuai 发表于 2014-10-28 14:43

AIX 用程序使profile文件立即生效

int modify_profile(char *str,char *value)
{
        assert(str != NULL && value != NULL);
        char strcmd = {0};
        int state =0;
        sprintf(strcmd,"sed 's/^export %s=.*/export %s=%s%s/' /home/bspdev1/.profile > /home/bspdev1/.profile_tmp",str,str,value,";"); /****替换字符串**且每个字段的值有;作为结尾的**/
        printf("%s\n",strcmd);
        system("cp /home/bspdev1/.profile /home/bspdev1/.profile_bak"); /*back up*/
        state = system(strcmd);
        printf("WEXITSTATUS(state) = %d\n",WEXITSTATUS(state));
        system("mv /home/bspdev1/.profile_tmp /home/bspdev1/.profile");
       
        return 0;
}int main()
{
        int state = 0;
        char str = "DBPASS";
        char value = "test888";
        printf("Before modify,%s=%s\n",str,getenv(str));
        modify_profile(str,value);
        state= system("cd /home/bspdev1 && . ~/.profile");/***修改.profile文件并使之立即生效,生效后用getenv()得到新的环境变量,但是目前不好用。。***/
        printf("WEXITSTATUS(state) = %d\n",WEXITSTATUS(state));
        printf("After modify,%s=%s\n",str,getenv(str));
}各位老手,我写了个程序,功能是:修改并保存profile文件,且使它立即生效,代码如上。
现在的问题是:profile文件可以被修改,但是并没有立即生效,程序中已经执行了system("cd /home/bspdev1 && sh .profile");为什么最后getenv()得到的环境变量还是修改之前的呢?我手动敲命令cd /home/bspdev1 && . ~/.profile,之后echo $DBPASS,就能得到新的环境变量。很疑惑,为什么用程序的方法不行呢?

guojinshuai 发表于 2014-10-28 16:29

楼主找了好多帖子,也问了很多人,终于懂了。
环境变量是进程私有的。。。。感觉这句话就能解决好多疑问了!
页: [1]
查看完整版本: AIX 用程序使profile文件立即生效