I am using a linux command prompt and I have noticed a difference when using the command ‘cd’ in the command prompt and using the command as an argument of the system call in a C program.
When I use the command prompt, the directory changes to the directory in the $home environment variable, but if I call it using the system call, then the directory doesn’t change?
Why is this happening?
The
cdcommand is a shell builtin — when it is executed by a shell script or on the command prompt, it is interpreted by that shell directly, and changes the working directory of the shell process.When you run a
cdcommand from within asystem()call, the command is passed to a shell subprocess, and changes the working directory of that process, which promptly exits. The working directory of the parent process is left unchanged.If you need to change the working directory of the current process, call
chdir()directly. Note that you can’t change the working directory of other processes (the child process is independent of its parent).