我正在尝试编写一个简单的 shell 程序,该程序能够解析由分号分隔的多个命令。例如 ls;pwd 将充当两个单独的命令。我已经弄清楚了单个命令,但无法解析多个命令。由于 Windows 不允许 fork() 我如何解析多个命令。我可以使用 strchr() 检查分号,但不知道如何构建一个解析多个命令的函数。任何帮助将不胜感激。
int main (int argc, char* argv[]){
char line[MAX];
char *newline;
char *input[50];
char newinput[MAX];
char *exitString="exit";
char *open ="ls";
char *executepwd ="pwd";
int i=0;
while (1){
getcwd(current_directory, sizeof(current_directory));
printf("$->");
fgets(line,MAX,stdin);
if (strchr(line,';')){
//I do not know how to parse multiple commands without fork()
printf("There are a lot of commands");
}
else{
//I could parse single commands but not multiple
if (strstr(input[0],exitString)){
printf("Exiting the program\n");
exit(0);
printf("\n");
}
else if
(strstr(input[0],open)){
ls();
printf("\n");
}
}
}
最佳答案
使用 getopt 解析并获取程序的输入参数
https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html
关于c - 为一个简单的shell程序解析多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58245239/