0

My Mac OS command line application is making Unix calls such as:

system("rm -rf /Users/stu/Developer/file);

perfectly successfully.

So why is the following not changing the current directory?

system("cd /Users/me/whatever");
system("pwd");    //cd has not changed
Sebastian
  • 7,670
  • 5
  • 38
  • 50
HenryRootTwo
  • 2,572
  • 1
  • 27
  • 27

1 Answers1

4

Because

system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed.

So each command is executed independently, each in a new instance of the shell.

So your first call spawns a new sh (with your current working directory), changes directories, and then exits. Then the second call spawns a new sh (again in your CWD).

See the man page for system().


The better solution is to not use system. It has some inherent flaws that can leave you open to security vulnerabilities. Instead of executing system() commands, you should use the equivalent POSIX C functions. Everything that you can do from the command-line, you can do with C functions (how do you think those utilities work?)

  • Instead of system("rm -rf ...") use this.
  • Instead of system("cd ...") use chdir().
  • Instead of system("pwd ...") use getcwd().

There are some differences, of course, but these are the fundamental equivalents of what you're trying to do.

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328