0

i'm working on a project, and running into a little problem. It's designed to be a simple shell, and right now, I'm working on entering the built in commands (pwd, cd, exit). I've got all but CD working.

The parsing works, and the different segments of the command and arguments are put into an array, so right now I have this:

void cd()
{
  chdir(commands[1].c_str());

  reset();
}

I run that, with a valid path that is in that directory, but it doesn't change. What am I missing?

Thanks!

  • 1
    If it isn't working, check the return status of `chdir` and `errno` that will tell you what is wrong. Do you have execute permissions on the directory to which you are cd'ing? – Michael Albers Feb 16 '16 at 05:10
  • @MichaelAlbers Just tried that, added the errno.h header and added cout for it in that same function, nothing got returned, so not looking like I'm getting any errors anywhere. And no warnings on compile, that all works fine – timgregoire Feb 16 '16 at 05:16
  • 1
    What do you mean "nothing got returned"? By definition, chdir returns an int. Do you mean it returned zero? How do you know the directory doesn't change? – Michael Albers Feb 16 '16 at 05:18
  • @MichaelAlbers Yes, returned a 0. – timgregoire Feb 16 '16 at 05:25
  • @MichaelAlbers Can tell directory doesn't change because immediately after, when I run a PWD, (getenv("PWD")), it still shows the original directory that the program was launched in – timgregoire Feb 16 '16 at 05:26
  • 1
    The `chdir()` system call doesn't affect your shell's environment variables, and hence not `PWD` in particular. The regular shell sets the value in `$PWD` when you execute `cd`; the value in `$PWD` doesn't change unless the shell does change it. – Jonathan Leffler Feb 16 '16 at 05:41

1 Answers1

3

You comment:

Can tell directory doesn't change because immediately after, when I run a PWD, (getenv("PWD")), it still shows the original directory that the program was launched in.

You're checking the current working directory incorrectly. See chdir() not affecting environment variable PWD

Instead of using getenv("PWD") use getcwd.

Community
  • 1
  • 1
Michael Albers
  • 3,721
  • 3
  • 21
  • 32