6

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"

3 Answers3

7

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.

caf
  • 233,326
  • 40
  • 323
  • 462
  • so what does PWD imply in this sense? The present working directory has already changed. –  Sep 04 '10 at 11:35
  • 2
    PWD is the working directory in the shell. The C program has a different working directory - it starts at the same as the calling shell then chdir changes the C program's working directory vut cannot affect the shell's directory – mmmmmm Sep 04 '10 at 11:53
  • 2
    @crypto: Environment variables aren't magic. They only change when an application explicitly changes them, so if your application never changes `PWD` then the meaning of `PWD` is "the current directory when the application was started". – caf Sep 04 '10 at 11:54
3

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

Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
  • so if i wrote this code as part of my own shell, should i change the PWD variable? Will there be any specific need for it? –  Sep 04 '10 at 12:29
  • @crypto, does your shell need it? That would depend on what you're doing with your shell. I don't even know if csh has PWD. – Paul Tomblin Sep 04 '10 at 13:02
  • point taken, i just mean that, is it the shell's job to maintain the environment variables, or should they just represent the state when the shell started? –  Sep 04 '10 at 13:31
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.

Javert93
  • 624
  • 6
  • 7