Question

I am creating a shell that can execute commands from user input on the terminal. It also has a history feature.

Everything works fine right now. The only part I am stuck on is that if the user enters a "!!" the most recent command should EXECUTE, and if the user enters a "! n" the nth command should EXECUTE. However, when I run it, nothing executes when I type in those commands.

The get_recent_command() and search_in_list_for_n() functions are returning the correct command, but when I put the result of those functions in place of where "args[0]" should be in the execvp() call, nothing happens.

Not sure. Thanks in advance! I tried null terminating the command before I added the command to the list, but it still didn't work. I am not sure what else I can do... Thank you so much in advance!

NOTE: Linked List code reused from site: http://www.thegeekstuff.com/2012/08/c-linked-list-example/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

#define MAX_LINE 80 //Maximum number of characters for a commandline

struct test_struct
{
    char *str;
    struct test_struct *next;
};

struct test_struct *head = NULL;
struct test_struct *curr = NULL;

struct test_struct* create_list(char * str)
{
    printf("\n creating list with headnode as %s\n",str);
    struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
    if(NULL == ptr)
    {
        printf("\n Node creation failed \n");
        return NULL;
    }
    ptr->str = str;
    ptr->next = NULL;

    head = curr = ptr;
    return ptr;
}

struct test_struct* add_to_list(char * str, bool add_to_end)
{
    if(NULL == head)
    {
        return (create_list(str));
    }

    if(add_to_end)
        printf("\n Adding node to end of list with value %s\n",str);
    else
        printf("\n Adding node to beginning of list with value %s\n",str);

    struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
    if(NULL == ptr)
    {
        printf("\n Node creation failed \n");
        return NULL;
    }
    ptr->str = str;
    ptr->next = NULL;

    if(add_to_end)
    {
        curr->next = ptr;
        curr = ptr;
    }
    else
    {
        ptr->next = head;
        head = ptr;
    }

    return ptr;
}

struct test_struct* search_in_list(char * str, struct test_struct **prev)
{
    struct test_struct *ptr = head;
    struct test_struct *tmp = NULL;
    bool found = false;

    printf("\n Searching the list for value [%s] \n",str);

    while(ptr != NULL)
    {
        if(ptr->str == str)
        {
            found = true;
            break;
        }
        else
        {
            tmp = ptr;
            ptr = ptr->next;
        }
    }

    if(true == found)
    {
        if(prev)
        *prev = tmp;
        return ptr;
    }
    else
    {
        return NULL;
    }
}

int countList(void)
{
    struct test_struct *ptr = head;
    int i = 0;
    while(ptr != NULL)
    {
        i++;
        ptr = ptr->next;
    }

    return i;
}

void print_list(void)
{
    int i = 1;
    int listCount = 0;
    struct test_struct *ptr = head;

    listCount = countList();
    printf("\n -------HISTORY START------- \n");
    while(ptr != NULL && i < 11)
    {
        printf("\n %i %s \n", listCount, ptr->str);
        ptr = ptr->next;
        i++;
        listCount--;
    }
    printf("\n -------HISTORY END------- \n");

    countList();
    i = 0;
    return;
}

char* get_recent_command(void)
{
    int listCount = 0;
    int i = 0;
    listCount = countList();

    if(listCount > 1)
    {
        struct test_struct *ptr = head;
        while(ptr != NULL && i < 1)
        {
            i++;
            ptr= ptr->next;
        }
        return ptr->str;
    }
    else
    {
        printf("No recent commands entered yet\n");
        return NULL;
    }
}

char* search_in_list_for_n(int n, struct test_struct **prev)
{
    int i = 0;
    int listCount = 0;
    int tempCount = 0;
    listCount = countList();
    tempCount = countList();

    if(listCount >= n)
    {
        struct test_struct *ptr = head;
        struct test_struct *tmp = NULL;
        bool found = false;

        while(tempCount != n)
        {
            i++;
            ptr = ptr->next;
            tempCount--;
        }
        return ptr->str;
    }
    else
    {
        printf("No such command found");
        return NULL;
    }
}

//Sets up shell function
void shellInput(char userInput[], char *args[], int ampersand);

int main(void)
{
char *str = " ";
char *str2 = " ";
char *str3 = " ";
struct test_struct *ptr = NULL;
int count = 0;

char *args[MAX_LINE/2 + 1]; //Holds individual arguments
int shouldRun = 1; //While loop continues to run if this equals 1
char userInput[MAX_LINE]; //Stores each character from user input
int ampersand; //Represents ampersand from commandline
pid_t pid;
pid_t pid2;
int n;

while(shouldRun)
{
    ampersand = 0; //If ampersand equals 1 at any point, the user entered an ampersand, so the parent will run concurrently
    printf("\nosh>");
    fflush(stdout);

    shellInput(userInput, args, ampersand); //Initiates shell
    count++;

    pid = fork();

    if(pid == 0)
    {
        if (args[1])
        {
            n = atoi(args[1]);
        }
        if(!(strncmp(args[0], "history", 7)))
        {

            print_list();
        }
        else if(!(strncmp(args[0], "!!", 2)))
        {
            str = get_recent_command();
            printf("str %s", str);

            if(execvp(str, args) < 0)
            {
                printf("execvp failed");
                exit(1);
            }
            else
            {
                printf("executing...");
                fflush(stdout);
                execvp(str, args);
            }
        }
        else if(!(strncmp(args[0], "!", 1)))
        {
            str3 = search_in_list_for_n(n,NULL);
            printf("search_in_list_for_n: %s", search_in_list_for_n(n,NULL));
            execvp(str3, args);
        }
        else
        {
            printf("executing...");
            fflush(stdout);
            execvp(args[0], args);
        }
        exit(0);
    }
    else if(ampersand == 0)
    {
        wait(&pid);
    }
    }
free(str);
return 0;
}

void shellInput(char userInput[], char *args[], int ampersand)
{
int commLength; //Length of command
int i; // Index for loop
int inputIndex = -5; //Represents the first index of each command parameter
int ParamCount = 0; //Number of parameters on command line (number of arguments)
char str [MAX_LINE];
char str2 [MAX_LINE];
char test = ' ';
char* temp;
char testing [MAX_LINE];
testing [0] = '\0';
char *strTest = " ";

strncpy(str2, &testing[0], 1);

//Reads user input from command line
commLength = read(0, userInput, MAX_LINE);

for(int k = 0; k < commLength; k++)
{
    strncpy(str, &userInput[k], 1);
    strcat(str2, str);
}

strTest = (char *)malloc(MAX_LINE + 1);
strcpy(strTest, str2);
strTest[MAX_LINE] = '\0';
add_to_list(strTest, false);
for(int q = 0; q < commLength; q++)
{
    printf("%c",userInput[q]);
}

//if user presses ctrl + d, the shell will exit
if (commLength == 0)
{
    exit(0);
}

//Loops through every character in the userInput array
for(i = 0; i < commLength; i++)
{
    //Checks a character from userInput array
    switch(userInput[i])
    {
            //If there is a space character, the command parameter upto that space will be stored into args
        case ' ':
            if(inputIndex != -5)
            {
                args[ParamCount] = &userInput[inputIndex]; //stores parameter into args array
                ParamCount++; //Increments number of arguments
                inputIndex = -5; //Resets index for the next command
                userInput[i] = '\0'; //Creates a C string
            }

            break;

            //If there is a new line character no more parameters will be stored
        case '\n':
            if(inputIndex != -5)
            {
                args[ParamCount] = &userInput[inputIndex]; //Last parameter is stored
                ParamCount++;
                userInput[i] = '\0';
                args[ParamCount] = NULL;//Since this was the last command, everything after should be null
            }
            break;

            //If there is a character besides space or newline (usually should be)
        default:
            if(inputIndex == -5)
            {
                inputIndex = i; //This occurs everytime a new command parameter has been found
            }

            if(userInput[i] == '&')
            {
                ampersand = 1;
                userInput[i-1] = '\0'; //Makes the parameter before the ampersand into a C string
            }
            //*note*: This default case will not carry out a function inbetween when the first command parameter has been found and until the next is found
    }
}

//Prints the arguments
for(i = 0; i <= ParamCount; i++)
{
    printf("args [%i]: %s\n", i, args[i]);
}
}
Was it helpful?

Solution

Your lack of information is going to cause me to make the following assumptions:

  • test_struct.str refers to a command in its entirety, e.g. "ls -la", "ps u".
  • You append new history items to the start of your list

When you pass print_recent_list() to execvp, you are passing the entire command, including its arguments. A quick glance at the man pages reveals that execvp()'s first argument "points to a pathname that identifies the new process image file". Essentially, you are looking for a process called ls -la, which makes no sense; the command is simply ls. You need to re-tokenize the string you get back from print_recent_list(), replacing args with the result of that tokenization and then calling print_recent_list(args[0], args) like you were in the else case.

(You're cutting it close asking this question the day before the assignment's due! I won't tell Dr. Knox).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top