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.
exectype commands usually run in their own environment. As in, they won't affect anything else, like the process you called them from.