i`m trying to simulate a terminal, and in my code almost all commands execute just fine, but the commands cd folder and cd .. when i try to execute those nothing happends, can any one help me with this
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXLEN 100
#define TRUE 1
#define FALSE 0
typedef struct command {
char *cmd; // string apenas com o comando
struct command *next; // apontador para o próximo comando
} COMMAND;
COMMAND *insert(COMMAND *list, char *cmd);
COMMAND *startList();
int strCompare(char *str1, char *str2);
int strLenght(char *str);
int main(void) {
char command[MAXLEN] = "start";
int id, return_command = 0;
COMMAND *commands = startList();
char exit_com[5] = "exit\0";
int r;
while(r = strCompare(command, exit_com)){
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL){
fprintf(stdout, "%s: ", cwd);
}
fgets(command, MAXLEN, stdin);
commands = insert(commands, command);
id = fork();
if (id == 0){
return_command = system(command);
if (return_command == -1){
printf("\nErro ao executar o comando '%s'\n", command);
exit(0);
}
COMMAND *c = commands;
while(c != NULL){
printf("%s\n", c->cmd);
c = c->next;
}
exit(0);
}
wait(id);
}
return 0;
}
int strCompare(char *str1, char *str2){
char aux = str2[0];
int i = 0;
while(aux != '\0'){
if (str1[i] != str2[i])
return 1;
aux = str2[++i];
}
return 0;
}
COMMAND *startList(){
return NULL;
}
COMMAND *insert(COMMAND *list, char *cmd){
COMMAND *newCommand = (COMMAND*) malloc(sizeof(COMMAND));
newCommand->cmd = cmd;
newCommand->next = list;
return newCommand;
}
It's because the system
function starts a new process, so every command you run through system
will be only in that process. That's why shells commonly handles commands like cd
internally.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.