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.