这是我想做的:
用户需要在提示符下输入命令,程序将评估该命令以知道该做什么。
如果找不到命令,则 shell 将返回错误“找不到命令!”。
如果用户输入命令 EXIT,那么程序应该退出。
为简单起见并避免用户在没有输入任何内容的情况下按下回车的问题,我们将假设用户总是会输入一些内容。
不会使用空字符串。我应该用一个循环来做到这一点,这就是我想要做的:
例子:
shell.exe
shell >测试
找不到命令!
shell >test2
找不到命令!
shell >退出
>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char command[20];
while (command != "exit") {
//check with an if statement for valid commands
printf("Enter a command:\n");
gets(command);
}
if (command == "exit") {
//program should exit
}
return 0;
}
最佳答案
使用popen()
或 system()
. Popen 为 i/o 提供了一个处理程序,而系统则给了狗屎,但是您仍然可以重定向到命令行上的管道(“<”和“>”),并从那里按自己的方式读写 i/o。
关于c - 如何编写一个评估 shell 命令的 c 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39932881/