gpt4 book ai didi

每行有多个命令的命令行解释器

转载 作者:太空宇宙 更新时间:2023-11-04 04:25:07 25 4
gpt4 key购买 nike

我想编写一个命令行解释器,每行包含多个命令。

我用 C 写了一个程序,每行 1 个命令,但如果我输入更多命令不起作用,命令输入如下: ls -l ;密码;猫文件; ls.

首先我解析 args,我将它们放入数组中并且我有这个函数:

pid_t pid;
pid = fork();

switch(pid) {
case -1:
printf("DEBUG:Fork Failure\n");
exit(-1);
case 0:
execvp(cmd[j], cmd);

if(execvp(cmd[j], cmd) == -1) {
printf("Command Not Found\n");
exit(0);
}

default:
wait(NULL);
printf("DEBUG:Child Finished\n");
}

我的解析器是:

printf("shell> ");

fgets (input, MAX_SIZE, stdin);

if ((strlen(input)>0) && (input[strlen (input) - 1] == '\n')) {
input[strlen (input) - 1] = '\0';
}


printf("INPUT: %s\n", input);

cnd = strtok(input, " ;");

int i = 0;

while(cnd != NULL) {
cmd[i] = cnd;
i++;
cnd = strtok(NULL, ";");

我认为我必须使用管道来解决我的问题,但是如何呢?有什么想法吗?

抱歉英语不好

最佳答案

你解释它的方式,似乎是你想一个接一个地执行命令,但不让它们相互通信(此外,将 ls 的输出传递给 pwd 毫无意义)。

为此,解决方案很简单:将输入拆分为分号,并将每个命令作为单个命令处理(因为它就是这样)。

通过一些伪代码,它可能看起来像这样

input = read_next_line();
while ((next_command = get_next_command(input)) != NULL)
{
execute_command(next_command);
}

您可以使用例如strtok 或类似函数。

关于每行有多个命令的命令行解释器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42467122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com