user1779646 user1779646 - 1 year ago 66
Bash Question

Changing the directory of the shell through a C++ program

I'm trying to write a simple C++ program to execute Linux commands. I'm stuck at changing the directories (commands like

don't work). This is what I have so far:

system("echo -n '1. Current Directory is '; pwd");
system("chdir Desktop");

Answer Source

This is not possible, if you want to change the directory (i.e. cd, that is chdir(2) ...) of the shell which has invoked your program. So cd has to be a bash(1) builtin.

The reason is that chdir affects only the calling process (which would be your C program) not the parent process. Each process has its own current directory.

If you call system(3) it will fork(2) a new shell and execve(2) /bin/sh -c so only the forked shell can change its current directory.

You need to read Advanced Linux Programming.

Perhaps you want to call chdir directly inside your C program. This will affect the current process and all future child processes (including those started with system or popen library functions inside your C code) till their termination or some further call to chdir. But it won't affect the shell in your terminal (where you started your C program).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download