c - 如何在 if-else 语句中使用多个 execvp 调用?

标签 c shell linked-list execvp

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

现在一切正常。我唯一坚持的部分是,如果用户输入“!!”最近的命令应该执行,如果用户输入“!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]);
}
}

最佳答案

您缺乏信息将使我做出以下假设:

  • 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 案例中一样。

(你在作业到期前一天问这个问题就结束了!我不会告诉诺克斯博士)。

关于c - 如何在 if-else 语句中使用多个 execvp 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21749500/

相关文章:

c - 为什么 Valgrind 报告 "Invalid read of size 2"?

c - realloc 在第二次调用时失败

c - sqlite3_*() 的正常例程是否有内存泄漏?

shell - 在 Jenkinsfile 的 shell 命令中为 Jenkins 管道使用参数

c - 为什么这个多项式加法不起作用?

c - 实现链表时指针的奇怪问题

c - Raspberry Pi GCC Makefile 和程序结构

linux - 菜单驱动的 Shell 脚本 bash

bash - Shell Bash : How to prompt a user to select from a dynamically populated list?

c - C 中的简单链表