Execute C program till Ctrl+C hit in the terminal

时光怂恿深爱的人放手 提交于 2019-12-23 17:43:38

问题


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.

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.

What I was thinking was of writing a do while loop like the following

do{ /Computation/ } while(Ctrl+C is not hit)

But i dont know how to check for the Ctrl+C input from the user.

Any suggestions will be appreciated.

Thanks


回答1:


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);
    /* ... */
}



回答2:


Ctrl+C will send your program a signal (SIGINT), if you DON'T set up a handler for it will cause your program to exit. So all you have to do is write

do { 
  //computation
} while(1);

and that will do what you want

EDIT: To do what you REALLY wanted without needing a signal handler, and avoiding doing things that might result in the compiler's optimizations breaking your code you can do this:

#include <signal.h>
/* ... */

int main() {
    sigset_t set, oldset;

    sigemptyset(&set);

    /* ... */

    sigaddset(&set, SIGINT);
    sigprocmask(SIG_BLOCK, &set, &oldset);
    do {
        sigset_t pending_set;
        /* ... */
        sigpending(&pending_set);
    } while(!sigismember(&pending_set, SIGINT));
    sigprocmask(SIG_SETMASK, &oldset, NULL);
    /* ... */
}



回答3:


When Ctrl-C is hit, a signal is sent to the program. The default behavior is that the program is terminated.

This means that you can let your program run forever, looping endlessly. When the user hits Ctrl-C, the program will abort.



来源:https://stackoverflow.com/questions/3189650/execute-c-program-till-ctrlc-hit-in-the-terminal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!