shell 的 C 输入循环
所以我正在创建一个非常简单的 C 程序,它只执行 shell 命令。这就是我到目前为止所拥有的:
#include <stdio.h>
int main()
{
char input[30];
fputs("$ ", stdout);
fflush(stdout);
fgets(input, sizeof input, stdin);
system(input);
}
它有效,但仅适用于一个命令。例如,如果我编译并输入 ./cmd 我会得到 $ 提示符。如果我输入 ls 我会得到我应该得到的东西。但随后它会退出并返回到常规系统 shell。我怎样才能让用户输入命令后返回到“$”输入。
So I'm working on creating a very simple C program that just preforms shell commands. This is what I have so far:
#include <stdio.h>
int main()
{
char input[30];
fputs("$ ", stdout);
fflush(stdout);
fgets(input, sizeof input, stdin);
system(input);
}
It works, but only for one command. For example if I compile and type ./cmd I get the $ prompt. If I type ls I get what I'm supposed to get. But then it exits and goes back to the regular system shell. How can I make it so after the user types a command it goes back to the "$" input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找的是循环;如果你想让退出条件由用户输入确定,实际上你可能需要一个无限循环(惯用的方式是
for(;;)
)和一个if
在输入采集之后,如果满足您的条件,则会导致中断
。您的退出条件可能涉及使用
strcmp
(来自
)来执行用户输入的字符串与退出命令之间的比较。What you're looking for are loops; if you want to have the exit condition determined by the user input, actually you probably need to have an infinite loop (the idiomatic way is
for(;;)
) and anif
after the input acquisition that results in abreak
if your condition is satisfied.Your exit condition will probably involve using
strcmp
(from<string.h>
) to perform the comparison between the string entered by the user and your exit command.您需要将代码放在循环内。例如:
while (1) { ... }
是一个无限循环。退出的唯一方法是以某种方式终止你的程序。为了能够使用命令退出循环,您需要在其中添加某种条件:strcmp()
进行比较以查看您是否键入了“exit”。如果是这样,那么break
语句将退出最近的循环,并且程序结束。You need to place your code inside a loop. For example:
The
while (1) { ... }
is an infinite loop. The only way to exit this would be to kill your program in some way. To be able to exit the loop with a command, you'll need to put some kind of condition inside it:The
strcmp()
does a compare to see if you typed "exit". If so, then thebreak
statement exits the nearest loop, and your program ends.您不需要任何循环,您需要一个
do while
循环,因为您总是希望至少执行一次system()
命令。此外,通过将关键字exit
作为中断条件,在调用system()
之前不需要额外的代码来检查input
,因为如果您使用strcmp()
作为 do-while 条件语句,exit
将终止您的 shell 和程序。输出
You don't want just any loop, you want a
do while
loop because you always want to perform thesystem()
command at least once. Also, by having the keywordexit
be your break condition, there is no need for extra code to checkinput
before you callsystem()
becauseexit
will kill both your shell and your program if you usestrcmp()
as the do-while conditional statement.Output