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
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?)
system("rm -rf ...")
use this . system("cd ...")
use chdir()
. system("pwd ...")
use getcwd()
. There are some differences, of course, but these are the fundamental equivalents of what you're trying to do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.