UNIX shel命令解释器 [英] UNIX shel command interpreter

查看:89
本文介绍了UNIX shel命令解释器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解析一个shell命令,以便可以用自己的shell执行它:

I was trying to parse a shell command so I can execute it with my own shell:

cp = (strtok(command, hash));            //Get the initial string (the command)
parameter[0] = (char*) malloc(strlen(cp)+ 1);                     //Allocate some space to the first element in the array
strncpy(parameter[0], cp, strlen(cp)+ 1);
for(i = 1; i < MAX_ARG; i++)
{
    cp = strtok(NULL, hash);                 //Check for each string in the array
    parameter[i] = (char*) malloc(strlen(cp)+ 1);
    strncpy(parameter[i], cp, strlen(cp)+ 1);                      //Store the result string in an indexed off array
    if(parameter[i]  == NULL)
    {
        break;
    }
    if(strcmp(parameter[i], "|") == 0)
    {
        cp = strtok(NULL, hash);
        parameter2[0] = (char*) malloc(strlen(cp)+ 1);
        strncpy(parameter2[0], cp, strlen(cp)+ 1);
        //Find the second set of commands and parameters
        for (j = 1; j < MAX_ARG; j++)
        {
            cp = strtok(NULL, hash);
            if (strlen(cp) == NULL)
            {
                break;
            }
            parameter2[j] = (char*) malloc(strlen(cp)+ 1);
            strncpy(parameter2[j], cp, strlen(cp)+ 1);
        }
        break;
    }



该部分应该将命令和参数存储在它们相应的数组中.但是,如果看到"|(管道)",则它假设要正确输入存储第二组命令参数.当我运行此代码时,当我做strlen(cp)== NULL



This portion is supposed to store the command and parameters in their corresponding arrays. However, if it sees a " | (a pipe) ", its suppose to enter store the second set of command parameter properly. When I run this code I get an error when I do strlen(cp) == NULL

推荐答案

strtok()时,会返回错误,返回指向下一个标记或NULL的指针.如果返回NULL,则对strlen()的调用将失败,因为您已向其传递了无效的指针.您的代码应为:
strtok() returns a pointer to the next token or NULL. If it returns NULL then the call to strlen() will fail because you have passed it an invalid pointer. Your code should read:
cp = strtok(NULL, hash);
if (cp == NULL)


请注意,您在代码的其他地方也有类似的错误;您必须先检查strtok()的返回值是否为空,然后再将其传递给任何其他函数.


Note that you have similar bugs elsewhere in your code; you must check that the return from strtok() is non-null before passing it to any other function.


这篇关于UNIX shel命令解释器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆