Question

I created a program where a signal call installs a new signal handler 'signum' and basically display a message whenever a terminal special char is pressed, such as CRTL-C.

I was wondering what if I wanted to keep track how many times CRTL-C was pressed? How can I go about implementing that? Thank you.

#include    <stdio.h>
#include    <signal.h>

main() {
    void    f(int);     
    int i;
    int count = 0;

    signal( SIGINT, f );        

    for (i = 0; i < 5; i++) {       
        printf("...I am waiting for you...\n");
        sleep(1);
    }

void f(int signum) {    
    printf("Haha, you clicked me!\n");
}
Était-ce utile?

La solution

Use a static variable:

void f(int signum) {
   static int cnt = 0;
   printf('Hahah, you clicked me %d time(s)!', ++cnt);
}

If you want that count available elsewhere, then use a global variable instead.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top