chdir() not affecting environment variable PWD

笑着哭i 提交于 2019-11-28 08:39:53

问题


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"


回答1:


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.




回答2:


"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.




回答3:


The PWD environment variable isn't automatically updated by chdir, so you'd have to do it explicitly using setenv. However, the getcwd function should still report the updated value automatically.



来源:https://stackoverflow.com/questions/3642050/chdir-not-affecting-environment-variable-pwd

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!