Run program C before pressing Ctrl + C in terminal

I am writing a program that repeatedly performs an operation until Ctrl + C suffers from a user in a Linux terminal. I program in C. Any ideas how I can implement this.

I tested my program using "for" loops with a condition, but now I want it to run until the user press Ctrl + C and break.

What I was thinking about is writing a do while loop, as shown below.

do {/ Calculus /} while (Ctrl + C misses)

But I don’t know how to check Ctrl + C input from user.

Any suggestions would be appreciated.

thank

+3
source share
3 answers

, spudd86. .

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

int execute;
void trap(int signal){ execute = 0; }

int main() {
    /* ... */
    signal(SIGINT, &trap);
    execute = 1;
    while(execute){
        /* ... */
    }
    signal(SIGINT, SIG_DFL);
    /* ... */
}
+12

Ctrl + C (SIGINT), , . , , ,

do { 
  //computation
} while(1);

,

: , , , , , , :

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

Ctrl-C . .

, , . Ctrl-C, .

0

Source: https://habr.com/ru/post/1753405/