0

I'm trying to use file.cpp to execute some simple bash commands. Code works for commands like ls, gedit, echo but fails at cd command.

Here is my file.cpp:

#include <stdio.h>
#include <unistd.h>

int main() {
    char *cd[] = {
        "/bin/bash",
        "-c",
        "cd /etc",
        NULL
    };
    execvp(cd[0], cd);
    return 0;
}

I execute it after compiling using ./file and my terminal output is,

rahul@Inspiron:~/Desktop$ g++ -Wno-write-strings file.cpp -o file
rahul@Inspiron:~/Desktop$ ./file 
rahul@Inspiron:~/Desktop$ 

Current directory didn't change to /etc. I have tried changing cd /etc to cd .., cd some_directory in file.cpp but no success.

Please point out what I'm doing wrong.

1
  • 2
    exec type commands usually run in their own environment. As in, they won't affect anything else, like the process you called them from. Commented Dec 9, 2016 at 1:15

1 Answer 1

2

Each process has its own current directory.

When you run /bin/bash -c "cd /etc" Bash starts up, changes its current directory, then exits. This happens regardless of whether you run it with exec, or fork then exec, or system, or by typing it into a shell, or some other way.

It has no effect on the current directory of the shell you ran it from.

Sign up to request clarification or add additional context in comments.

9 Comments

So Is there a way to see those changes in current terminal session?
@Rahul No there is not.
no - because there are no changes to the current session. You cannot do what you are trying to do. cd is a command built in to the shell, its not a program (vs ls or mkdir)
@Rahul actualy if you want to execute code in another directory you can, just put the full path in the exec - instead of '-c foo` say -c \home\joe\foo
@rahul: man 2 chdir
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.