我有一个用 C 编写的 shell 程序,当我尝试运行命令“ls |”时 (只是 ls 和一个管道,后面什么都没有),我的程序永远循环。您可以忽略 modePtr... 这个解析器所做的是从用户输入中获取一串字符,因此它正在解析命令“ls |” 我猜问题在于没有一个“案例”会导致空管道命令落入,从而导致无限循环?有什么建议么?
int parse(char *inputString, char *cmdArgv[], char **supplementPtr, int *modePtr)
{
int cmdArgc = 0, terminate = 0;
char *srcPtr = inputString;
//printf("parse fun%sends", inputString);
while(*srcPtr != '\0' && terminate == 0)
{
*cmdArgv = srcPtr;
cmdArgc++;
//printf("parse fun2%sends", *cmdArgv);
while(*srcPtr != ' ' && *srcPtr != '\t' && *srcPtr != '\0' && *srcPtr != '\n' && terminate == 0)
{
// Handles redirection/pipes
switch(*srcPtr)
{
// Background mode
case '&':
*modePtr = BACKGROUND;
break;
// Output mode
case '>':
*modePtr = OUTPUT_REDIRECTION;
*cmdArgv = '\0';
srcPtr++;
if(*srcPtr == '>')
{
*modePtr = OUTPUT_APP;
srcPtr++;
}
while(*srcPtr == ' ' || *srcPtr == '\t' || *srcPtr == '\0')
srcPtr++;
*supplementPtr = srcPtr;
chop(*supplementPtr);
terminate = 1;
break;
// Input mode
case '<':
*modePtr = INPUT_REDIRECTION;
*cmdArgv = '\0';
srcPtr++;
while(*srcPtr == ' ' || *srcPtr == '\t' || *srcPtr == '\0')
srcPtr++;
*supplementPtr = srcPtr;
chop(*supplementPtr);
terminate = 1;
break;
// Pipe mode
case '|':
*modePtr = PIPELINE;
*cmdArgv = '\0';
srcPtr++;
while(*srcPtr == ' ' || *srcPtr == '\t' || *srcPtr == '\0')
srcPtr++;
*supplementPtr = srcPtr;
//chop(*supplementPtr);
terminate = 1;
break;
}
srcPtr++;
}
// Process commands when these occur
while((*srcPtr == ' ' || *srcPtr == '\t' || *srcPtr == '\n') && terminate == 0)
{
*srcPtr = '\0';
srcPtr++;
}
cmdArgv++;
}
/*srcPtr++;
*srcPtr = '\0';
destPtr--;*/
*cmdArgv = '\0';
return cmdArgc;
}