- 论坛徽章:
- 0
|
- int modify_profile(char *str,char *value)
- {
- assert(str != NULL && value != NULL);
- char strcmd[1200] = {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[100] = "DBPASS";
- char value[1024] = "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,就能得到新的环境变量。很疑惑,为什么用程序的方法不行呢?
|
|