Home > Net >  Low level code for a shell in C that needs to be able to change directories using getcwd(), getenv()
Low level code for a shell in C that needs to be able to change directories using getcwd(), getenv()

Time:12-05

I am working on a project where I need to create a shell that is able to switch between directories and continuously output the current directory, exactly how it normally is in Linux.

Here is the code I have thus far

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>

#define BUFFERSIZE 1024

int main(int argc, char* argv[])
{
    char buf[BUFFERSIZE];
    int n;
    printf("1730sh:~$ \n");
    while ((n = read(STDIN_FILENO, buf, BUFFERSIZE)) > 0)
    {
        buf[n] = 0;
        buf[strlen(buf)-1] = '\0';
        int i = 0;
        char* array[10];
        char* token1 = strtok(buf, " ");
        char* newarray[10];
        int exitIndicator = 0;
        char* directOut;
        char* directory;

        while ((token1 != NULL))
        {
            array[i  ] = token1;
            token1 = strtok(NULL, " ");
        }//while

        array[i] = NULL;
        for (int j = 0; j < i; j  )
        {
            if (!strcmp(array[j], "cd"))
            {
                directory = array[j 1];
                int change = chdir(directory);
                exitIndicator = 1;
            }
        }
        printf("1730sh:~%s$ \n", directory);
    }
}

The problem with this code is after changing directories from the beginning, if I enter another command and run it, it goes back to its home directory.

Ps: in the full code, cat file1.txt works as it should, so just assume that it works and outputs what it should.

./main
1730sh:~$ 
cd Ghioalda-Edward-p3
1730sh:~Ghioalda-Edward-p3$ 
cat file1.txt
1730sh:~$ 

CodePudding user response:

If the command is not cd then you have these two lines:

char* directory;
printf("1730sh:~%s$ \n", directory);

You're printing using the uninitialized pointer directory, a pointer whose value (where it's pointing) is indeterminate, and that will lead to undefined behavior.

As a simple solution I recommend you create another variable, an array, to hold the current directory. Define that variable outside the main reading loop, and copy into that when you change directory.

So something like

char current_directory[256] = "";  // Initialize to the empty string

printf("1730sh:~$ \n");
while ((n = read(STDIN_FILENO, buf, BUFFERSIZE)) > 0)
{
    // ...

    if (!strcmp(array[j], "cd"))
    {
        strcpy(current_directory, array[j 1]);
        int change = chdir(current_directory);
    }

    // ...

    printf("1730sh:~%s$ \n", current_directory);
}
  • Related