c - 为一个简单的shell程序解析多个命令

标签 c

我正在尝试编写一个简单的 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/

相关文章:

c - 为什么 printf 中的格式标记为 restrict?

c - azure-iot-sdk-c 反序列化 JSON 负载

c++ - 使用 malloc 分配比现有内存更多的内存

c - 浮点值的输出有什么区别?

c - 如何使用内联汇编 (NASM) 进行文件 I/O

c++ - 使用 libcurl 编写 HTTPS SOAP 客户端

c++ - 为什么这段代码在实际的 BCM2837 (pi 3) 上运行时会挂起,但在 qemu 上运行良好

c++ - 在数组中获取和存储内存地址的问题

c++ - 我们可以在 MDI 应用程序的 View 中创建 ListCtrl 还是我们总是需要绘制它?

c - Spin Loop 在缓存一致性方面的开销