Tony Alexander
Tony Alexander

Reputation: 35

How to use chdir to change a directory?

I am currently working on creating my own linux shell. I can "ls" in my directory and much more. However, When I try and "cd" into a sub directory, it never actually changes. The code gets ran but does not actually change my directory. On my linux filesystem I have the directory

/    
    home
        testing
            foo.txt
            testingForShell
                bar.txt

To get the current directory, I am using...

void execute(string command, char *
    const * args, char * path) {
    int pid = -5;
    int child = -5;
    int status;
    pid = fork();
    if (pid == 0) {
        if (command.substr(command.length() - 2).compare("cd") == 0) {
            const char * currentPath;
            if ((currentPath = getenv("HOME")) == NULL) {
                currentPath = getpwuid(getuid()) -> pw_dir;
            }
            cout << (string(currentPath) + "/" + string(args[1])).c_str() << endl;
            int dir = chdir((string(currentPath) + "/" + string(args[1])).c_str());

        } else {
            char * pathArgs = strtok(path, ":");
            while (pathArgs != NULL) {
                try {
                    execv((string(pathArgs) + "/" + command).c_str(), args);
                } catch (...) {

                }
                pathArgs = strtok(NULL, ":");
            }
        }

        exit(0);
    } else {
        waitpid(-1, & status, 0);
    }
}

The first if inside the child process is if they are going to "cd" into a directory. The else is for other commands such as "ls". The cout prints out /home/testing/testingForShell but when I call "ls" again, it never went inside the directory to show bar.txt. Let me know if I have provided enough information. I am very confident I am using chdir wrong, but that might not be the case. NOTE: I am trying to change the directory in the script running, not the actual linux terminal that I started my script from.

Upvotes: 1

Views: 546

Answers (1)

rici
rici

Reputation: 241901

Changing working directory in a forked process will work fine... in that forked process.

But it doesn't do anything to the parent. So the next command that is executed is in the same working directory as before.

Upvotes: 1

Related Questions