Skip to content
Advertisement

Executing Bash commands using C code

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement