Hi,
I have to change working directory from my C program. For this I have used the following command:
execl("/bin/cd","cd","..",(char*)0);
but this command is not changing the directory?
Is anything wrong in this command or is there any other way to change working directory from C program?
views:
69answers:
3
+8
A:
To change the current directory you should use chdir
:
int chdir(const char *path);
On success it returns 0.
You can't use execl for several reasons:
cd
is typically a shell builtin command;- on most systems
/bin/cd
does not exists; on the very very few systems that have it, it changes the current directory and then spawns a child shell process; - the current directory is a process' property: if you change the current directory using
/bin/cd
, you'd lose the directory change as soon as the process terminates; - if you use a function from the
exec
family, the current process image is replaced with a new process image - you could usesystem
, but wouldn't fix the previous 3 problems.
Giuseppe Cardone
2010-09-24 08:20:31
+2
A:
What you are doing won't work because the exec
family of calls will actually replace your current program in the current process. In other words, you will have been terminated so that, when cd
is finished, your parent process will once again take over.
If you want to change the working directory for the current process, use chdir
. If you want to change it on exit, you're out of luck because your program itself is running in a separate process from the parent that started it.
So, unless you have some form of communication with the parent, that's not going to work.
paxdiablo
2010-09-24 08:26:12