执行C程序,直至按Ctrl + C在终端打 [英] Execute C program till Ctrl+C hit in the terminal
问题描述
我写一个程序,反复做,直到按Ctrl + C的操作是通过在Linux终端的用户打。我编程在C任何想法如何,我可以实现这一点。
I am writing a program that repeatedly does an operation till Ctrl+C is hit by the user in the Linux terminal. I am programming in C. Any ideas how i can implement this.
我以为我的测试程序符合条件循环,但现在我希望把它只要按Ctrl + C被用户打和中断运行。
I have tested my program by using "for" loops with a condition but now i want to make it run as long as Ctrl+C is hit by the user and interrupted.
我在想什么是写做的while循环类似于下面的
What I was thinking was of writing a do while loop like the following
做{
/的计算的/
}
而(Ctrl + C键是打不到)
do{ /Computation/ } while(Ctrl+C is not hit)
但我不知道如何检查由用户按Ctrl + C输入。
But i dont know how to check for the Ctrl+C input from the user.
任何建议将AP preciated。
Any suggestions will be appreciated.
感谢
推荐答案
一个信号陷阱会做的伎俩更清洁比spudd86的建议。这个例子可以显著得到改善,虽然
A signal trap will do the trick more cleanly than spudd86's suggestion. This example can be improved significantly, though.
#include <signal.h>
/* ... */
int execute;
void trap(int signal){ execute = 0; }
int main() {
/* ... */
signal(SIGINT, &trap);
execute = 1;
while(execute){
/* ... */
}
signal(SIGINT, SIG_DFL);
/* ... */
}
这篇关于执行C程序,直至按Ctrl + C在终端打的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!