Call cd command in c ++ using system ()

1

I'm trying to "program a shell" inside C ++ but I'm not able to use the cd (path) command it just will not, I searched and saw that when I use system() a new shell is created outside the directory we are in so I can not use it, what would be the solution?

PS: The other commands (from what I've tested) take as normal.

#include <stdio.h>
#include <stdlib.h>

#define LIMITE 256

int main (void){
char comando[LIMITE];


//Laço
while(1){
    printf("teste@teste-VirtualBox:~$ ");
    if(fgets(comando, sizeof(comando), stdin) != NULL){
        system(comando);
    }
}


return 0;

}
    
asked by anonymous 21.06.2017 / 21:27

2 answers

2

If you are doing a shell, rather than calling 'system' is calling 'fork' and 'execvp' under Linux or 'CreateProcess' under Windows. Some examples for Linux are given in English by others who are also making a shell:

link

link

Calling 'system' will create a new process that uses a shell to process the given command. If you give cd as a command, the new process will change its own path and will end, leaving the path of your program the same as before.

The 'cd' command is not a program that calls itself, so you have to make your shell recognize and process the 'cd' command by itself. To implement this command, you can call chdir to change the path.

    
28.06.2017 / 06:06
2

You can use chdir to force this change of directory to the system on linux

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

int main(void){
   //apontamos o terminal para /
   chdir("/");
   system("pwd");

   //apontamos o terminal para /home/kodonokami
   chdir("/home/kodonokami");
   system("pwd");
}

InwindowswecanhavethesameresultwithSetCurrentDirectory

#include<stdio.h>#include<stdlib.h>#include<windows.h>intmain(void){//apontamosoterminalparac:\SetCurrentDiretory("c:\");
   system("dir");

   //apontamos o terminal para c:\windows
   SetCurrentDiretory("c:\windows");
   system("dir");
}

If you put the commands in the same system separated by a semicolon, it also works (in windows you use & to separate), you can always use the cd when calling the system pass it to a variable that has the current directory and modify this variable when you need to change the directory

#include <stdio.h>
#include <stdlib.h>

int main(void){
   //isso é uma gambiarra '-'
   system("cd / ; pwd ; cd /home/kodonokami ; pwd");
}

Another way can be done by running the shell by the program as already mentioned by Kyale A

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

int main(void){
    execv("/bin/sh",NULL);
}

There are other forms besides those mentioned ^^

    
28.06.2017 / 09:14