Search code examples
linuxshellexecforkcd

Student Shell - cd not working


I'm working on a simple Linux Shell, it can fork() and call execvp(), but I recently added "build in functions" which need to NOT fork().

Here is the execution handling:

    if (strcmp(cmd, "exit") == 0) {
        exit = 1;
    }
    else if (builtIn(opt) == 0){
        execvp(cmd, opt);
    }
    else {
        pid_t pID = fork();

        if (pID == 0) { 
            execvp(cmd, opt);
        } else if (pID < 0) { 
            printf("\nFailed to fork\n");
        } else {
            wait(0);
        }
    }

builtIn() just checks the command and returns 1 or 0:

int builtIn(char * opt[]) {

    if (strcmp(opt[0], "cd")) {
        return 1;
    }
    return 0;
}

Solution

  • It's true that you need to avoid forking, but you also need to avoid executing. There is no /bin/cd that programs call to change directories.

    Instead of executing something, call the chdir system call with your path. If the user types cd /tmp, call chdir("/tmp")

    The current directory is a property of each process (as the open files or the umask value) You cannot call a program to change your current dir, as a program is a different process and will change effectively its directory (not yours). That's the reason of not existing a cd external command and to have to make a system call to change it.