[英]Command parsing UNIX shell C
我試圖創建一個程序,可以在其中解析用戶輸入的命令和參數到特定數組中(這些命令和參數將執行“ ls”,“ ls -l”,“ ls -l | wc”之類的命令,但是,我在解析時遇到問題:
//Split the command and store each string in parameter[]
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 (cp == NULL)
{
leave = 1;
break;
}
else
{
parameter2[j] = (char*) malloc(strlen(cp)+ 1);
strncpy(parameter2[j], cp, strlen(cp)+ 1);
}
}
}
if (leave == 1)
{
break;
}
}
如果(strlen(cp)== NULL)出現分段錯誤,我就會遇到問題。 一旦所有輸入都輸入到數組中,我試圖突破較大的for循環。 我可以成功地在數組中輸入正確的字符串元素,但是一旦完成就無法退出循環。
如果找不到更多令牌, strtok
可能會返回NULL指針。 因此,您必須在使用前檢查cp
值:
cp = strtok(NULL, hash);
if (cp != NULL)
{
........
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.