Will
Will

Reputation: 4469

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

Upvotes: 0

Views: 803

Answers (2)

Henok Tesfaye
Henok Tesfaye

Reputation: 9570

In addition to Luis answer. Even if there is a program cd in /bin, it won't work since each process have their own pwd(present working directory) so it changes pwd of the cd program not its parent, main shell.

Upvotes: 1

that other guy
that other guy

Reputation: 123650

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.

Upvotes: 3

Related Questions