如何使用if-else语句进行多个execvp调用?

时间:2014-02-13 09:07:08

标签: c shell linked-list execvp

我正在创建一个可以从终端上的用户输入执行命令的shell。它还具有历史功能。

现在一切正常。我坚持的唯一部分是,如果用户输入“!!”最近的命令应该是EXECUTE,如果用户输入“!n”,则第n个命令应该执行。但是,当我运行它时,当我输入这些命令时没有执行任何操作。

get_recent_command()和search_in_list_for_n()函数返回正确的命令,但是当我将这些函数的结果放在execvp()调用中“args [0]”的位置时,没有任何反应。

不确定。提前致谢!在我将命令添加到列表之前,我尝试使用null终止命令,但它仍然无法正常工作。我不确定我还能做什么......提前谢谢你!

注意:从网站重复使用的链接列表代码: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]);
}
}

1 个答案:

答案 0 :(得分:0)

您缺乏信息会导致我做出以下假设:

  • test_struct.str指的是一个完整的命令,例如"ls -la""ps u"
  • 您将新的历史记录项追加到列表的开头

当您将print_recent_list()传递给execvp时,您将传递整个命令,包括其参数。快速浏览手册页可以看出execvp()的第一个参数“指向标识新过程映像文件的路径名”。从本质上讲,您正在寻找一个名为ls -la的流程,这是没有意义的;该命令只是ls。您需要重新标记从print_recent_list()返回的字符串,将args替换为该标记化的结果,然后像print_recent_list(args[0], args)情况一样调用else

(你要在作业到期前一天将它问到这个问题!我不会告诉诺克斯博士)。