首页 > 解决方案 > 采用多字命令的基本 shell

问题描述

我正在尝试实现一个接受命令的外壳;但是,我无法让它正常工作。例如,如果我输入“ls -a”,我会得到:

无效选项——“”

尝试“ls --help”以获取更多信息。

作为初学者,我可能犯了一些严重的错误,所以请原谅我。另外,我会将读取命令的代码放入函数中。就像这样用于测试-谢谢。

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

int main()
{
    pid_t       pid;
    int         status;
    char* token;
    char* argv[20];
    char input[100];

    printf("AP> ");

    while (1)
    {
        fgets(input, 100, stdin);
        token = strtok(input, " ");

        int i = 0;
        //walk through other tokens
        while (token != NULL) {
            argv[i] = malloc(strlen(token) + 1);
            strncpy(argv[i], token, strlen(token));
            //argv[i] = token;
            i++;
            token = strtok(NULL, " ");
        }
        argv[i] = NULL; //argv ends with NULL

        pid = fork();

        if (pid < 0)
        {
            perror("fork error");
            return EXIT_FAILURE;
        }

        else if (pid == 0)
        {
            // child process
            execvp(argv[0], argv);
            perror("execl error");
            return EXIT_FAILURE;
        }

        else {
            // parent process
            if (waitpid(pid, &status, 0)<0)
            {
                perror("waitpid error");
                return EXIT_FAILURE;
            }
        }
        printf("AP> ");
    }

    return 0;
}

标签: clinuxshell

解决方案


input如果您在内部 while 循环之后插入以下循环,那么您会看到您没有在 while 循环开始之前删除末尾的换行符。

for (i=0; argv[i]; i++)
   printf("argv[%d] = '%s'\n", i, argv[i]);

或者,您可以使用:

" \n"

作为你的分隔符,而不仅仅是

" "

推荐阅读