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
You're better off using int chdir(const char *path);
found in unistd.h
.
When a fork is done the environment variable CWD(current working directory) is inherited by the child from the parent.If fork and exec is done as usual then the child calls chdir() which simply changes the directory to the new directory and exits but this does not affect the parent.Hence, the new environment is lost..
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.)
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.