简体   繁体   English

chdir()不影响环境变量PWD

[英]chdir() not affecting environment variable PWD

When I use chdir() to change the current working directory, why doesn't the getenv("PWD") give the present working directory? 当我使用chdir()更改当前工作目录时,为什么getenv(“PWD”)不提供当前工作目录? Do I need to setenv("PWD",newDir,1) also? 我还需要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));      
    }
}

Output: (location of the executable is /home/user) 输出:(可执行文件的位置是/ home / user)

changedir /boot changeir / boot

Directory changed. 目录已更改。 The present working directory is "/home/user" "/boot" 目前的工作目录是“/ home / user”“/ boot”

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. 它是在正常事件运行中设置和更新PWD的shell,因此它仅反映shell已知的当前目录的更改。

"getenv" gets PWD from the environment that the program started from. “getenv”从程序开始的环境中获取PWD。 "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. 等待当前工作目录的“PWD”是由shell维护的,并且由于您更改了从shell而不是shell启动的程序中的目录,因此PWD在环境中没有更改。

You'll probably also notice that when your program ends, the shell is still at the directory you started at. 您可能还会注意到,当程序结束时,shell仍然位于您启动的目录中。 The shell hasn't changed directory, so PWD hasn't changed. shell没有更改目录,因此PWD没有更改。

The PWD environment variable isn't automatically updated by chdir , so you'd have to do it explicitly using setenv . chdir不会自动更新PWD环境变量,因此您必须使用setenv显式执行此操作。 However, the getcwd function should still report the updated value automatically. 但是, getcwd函数仍应自动报告更新的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM