chdir() 不影响环境变量 PWD
当我使用 chdir() 更改当前工作目录时,为什么 getenv("PWD") 不给出当前工作目录?我还需要 setenv("PWD",newDir,1) 吗?
void intChangeDir(char *newDir)
{
if( chdir(newDir)==0 )
{
printf("Directory changed. The present working directory is \"%s\" \"%s\"\n",getenv("PWD"),getcwd(NULL,0));
}
else
{
printf("Error changing dir %s\n",strerror(errno));
}
}
输出:(可执行文件的位置是/home/user)
changedir /boot
目录已更改。当前工作目录是“/home/user”“/boot”
When I use chdir() to change the current working directory, why doesn't the getenv("PWD") give the present working directory? Do I need to setenv("PWD",newDir,1) also?
void intChangeDir(char *newDir)
{
if( chdir(newDir)==0 )
{
printf("Directory changed. The present working directory is \"%s\" \"%s\"\n",getenv("PWD"),getcwd(NULL,0));
}
else
{
printf("Error changing dir %s\n",strerror(errno));
}
}
Output: (location of the executable is /home/user)
changedir /boot
Directory changed. The present working directory is "/home/user" "/boot"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
“getenv”从程序启动的环境中获取 PWD。等于当前工作目录的“PWD”是由 shell 维护的,并且由于您更改了从 shell 而不是 shell 启动的程序中的目录,因此
PWD
在环境中没有更改。您可能还会注意到,当程序结束时,shell 仍然位于您启动时所在的目录。 shell 没有更改目录,因此 PWD 没有更改。
"getenv" gets PWD from the environment that the program started from. "PWD" equalling the current working directory is something maintained by the shell, and since you changed directory in the program you started from the shell rather than the shell,
PWD
hasn't changed in the environment.You'll probably also notice that when your program ends, the shell is still at the directory you started at. The shell hasn't changed directory, so PWD hasn't changed.
PWD 环境变量不会由
chdir
自动更新,因此您必须使用setenv
显式更新。但是,getcwd
函数仍应自动报告更新后的值。The PWD environment variable isn't automatically updated by
chdir
, so you'd have to do it explicitly usingsetenv
. However, thegetcwd
function should still report the updated value automatically.是的,如果您想更改环境变量,则必须明确执行此操作。
它是在正常事件运行中设置和更新 PWD 的 shell,因此它仅反映 shell 已知的当前目录的更改。
Yes, if you want to change the environment variable, you have to explicitly do that.
It's shell that sets and updates
PWD
in the normal run of events, so it only reflects changes of the current directory known to the shell.