0

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;
}

2 Answers 2

2

You may like to use chdir call to change the working directory of your shell process. The child processes started by system call inherit the working directory from the parent process

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.