【问题标题】:Implementing a command line interpreter in C, special case用 C 实现命令行解释器,特殊情况
【发布时间】:2023-03-06 14:33:01
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

#define BUFFER 64

char *read_command(void);
char **parse_line(char *line);
int execute(char **arguments);

int main(void)
{
    char *command = NULL;
    char **arguments;
    int status;

    do
    {
        printf("protoulis_7968> ");
        command = read_command();
        arguments = parse_line(command);
        status = execute(arguments);

        free(arguments);
        free(command);

    }while(status);
}

char *read_command(void)
{
    char *command = NULL;
    ssize_t buf = 0;
    getline(&command, &buf, stdin);
    return command;
}

char **parse_line(char *line)
{
    int buffer = BUFFER;
    int pos = 0;
    char **tokens = malloc(buffer * sizeof(char*));
    char *token;
    if (!tokens)
    {
        printf("Error allocating memory with malloc\n");
        exit(0);
    }
    token = strtok(line, " \t\r\n\a");
    while(token != NULL)
    {
        tokens[pos] = token;
        pos++;

        if (pos >= buffer)
        {
            buffer += BUFFER;
            tokens = realloc(tokens, buffer * sizeof(char*));
            if (!tokens)
            {
                printf("Error reallocating memory!\n");
                exit(0);
            }
        }
        token = strtok(NULL, " \t\r\n\a");
    }
    tokens[pos] = NULL;
    return tokens;
}

int execute(char **arguments)
{
//  printf("%*c\n", arguments);
    int pid, waitPid, status;

    pid = fork();

    if(pid == 0)    //child process
    {
        if (execvp(arguments[0], arguments) == -1)
            perror("Error with EXECVP\n");
    }
    else if (pid < 0)
        perror("Error PID < 0\n");
    else    //parent process
    {
        do
        {
            waitPid = waitpid(pid, &status, WUNTRACED);
        }while(!WIFEXITED(status) && !WIFSIGNALED(status));
    }
    return 1;
}

好吧,我用 C 语言编写了模拟命令行解释器的上述代码。我希望能够通过在一行中输入多个命令来执行它们。我的意思是我想作为输入传递,例如: ls -l ;触摸你好.c;密码。通过这一整行后,我想用分号分隔命令,并让系统以任何顺序执行每个命令。我相信我必须使用 strtok 函数,但做了很多尝试却什么也没做。任何帮助将不胜感激!

【问题讨论】:

  • 好吧,在这个项目中,我并不真正关心命令的执行顺序。我只关心用户是否键入退出命令。然后我想先执行所有命令,最后执行exit命令。

标签: c shell command-line


【解决方案1】:

strtok 在您的情况下是不够的。原因是它会将您带到下一个子命令,但要能够执行此子命令,您必须将其作为单个字符串。

解决这个问题的两种方法:

  1. 计算有多少';'有,用 '\0' 替换它们,让内存中有几个连续的字符串,然后一个一个地执行。
  2. 编写一个函数,将您的命令字符串拆分为一个二维子命令数组,然后一个一个地执行它们。

如果您需要一些灵感,这里有一个代码:

【讨论】:

  • 谢谢!我可能会尝试您建议的第一种方法并让您知道。也感谢您的灵感代码!
  • @TeoProtoulis 很乐意为您提供帮助。如果对您的问题有帮助,请将答案标记为已接受。
  • 我一试就行!
猜你喜欢
  • 1970-01-01
  • 2013-02-02
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
  • 2012-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多