I know that cd
is a shell built-in ,and I can run it by using system()
.
But is that possible to run the cd
command by the exec()
family, like execvp()
?
Edit: And I just noticed that system("cd")
is also meaningless。Thanks for the help of everyone.
The exec family of functions replaces the current running process with a new process. It can be used to run a C program by using another C program. It comes under the header file unistd.
- is a special argument for the cd command: cd - means to go back to the previous current directory. To implement this functionality, you need to keep track of the last directory cd changed to. Use the getcwd() function for that before calling chdir and if successful, keep this previous directory in a global array.
exec
loads an executable file and replaces the current program image with it. As you rightly noted, cd
is not an executable file, but rather a shell builtin. So the executable that you want to run is the shell itself. This is of course what system()
does for you, but if you want to be explicit about it, you can use exec
:
execl("/bin/sh", "-c", "cd", (const char *)0);
Since this replaces your current process image, you should do this after fork()
ing off a new process.
However, this entire procedure has absolutely no effect. If you want to change the directory in your current process, use chdir()
.
No it is not, and it would be of no use. chdir
(the function that changes a process's current directory) only affects the process that calls it (and its children). It does not affect its parent in particular.
So exec
ing cd
has no point, since the process would exit immediately after having changed directories.
(You could exec something like bash -c cd /tmp
if you really want to, but as I said, this is fruitless.)
You're better off using int chdir(const char *path);
found in unistd.h
.
While, as already stated system("cd xxx")
wouldn't change your application current directory, it is not completely useless.
You can still use system exit status to know if changing your current directory to the one stated would succeed or not.
Similarly, if you like complex solutions, you could also do the same with fork/exec, either with exec'ing /bin/sh -c cd xxx
or simply /bin/cd xxx
with OSes that provide an independent cd
executable.
I would however recommend this non overkill faster equivalent access("xxx", X_OK|R_OK)
Note: All POSIX compliant OSes must provide an independent cd executable. This is at least the case with Solaris, AIX, HP-UX and Mac OS/X.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With