如何捕获SIG中使用SIGINT的次数?

时间:2013-04-14 18:13:41

标签: c function

如何在程序结束前捕获SIGINT的使用次数? 例如:在只使用SIGQUIT时结束的程序中,告诉我用户在结束前按ctr-c(使用SIGINT)的次数。

到目前为止我已经做到了这一点:

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

void sigproc1(int var); 
void sigproc2(int var);

int main()
{

    signal(SIGINT, sigproc1)  //SIGINT - interactive attention request sent to the program.
    signal(SIGQUIT, sigproc2) //SIGQUIT - The SIGQUIT signal is similar to SIGINT, except that it's controlled by a different key—the QUIT character, usually C-\—and produces a core dump when it terminates the process, just like a program error signal. You can think of this as a program error condition “detected” by the user.


}

void sigproc1(int var)
{

    signal(SIGINT, sigproc1);
    signal(SIGINT, sigproc2);

    printf("You have pressed ctrl-c\n");

    //Save the number of times that it received the SIGINT signal
//Print the number of times that it received the SIGINT signal
}

void sigproc2(int var)

    exit(0); //Normal exit status.
}

1 个答案:

答案 0 :(得分:1)

我使用了一个名为ct的全局变量(来自count),我在sigint函数中递增并显示。

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

int ct = 0;

void sigint(int sig)
{
    printf("You have pressed ctrl-c %d times\n", ++ct);
}

void sigquit(int sig){
    exit(0); // use CTRL+\ to exit the program since CTRL+c displays those stats
}

int main()
{
    signal(SIGINT, sigint);
    signal(SIGQUIT, sigquit);

    while(1){}
}

示例输出:

[paullik@eucaryota tmp]$ ./a.out 
^CYou have pressed ctrl-c 1 times
^CYou have pressed ctrl-c 2 times
^CYou have pressed ctrl-c 3 times
^CYou have pressed ctrl-c 4 times
^CYou have pressed ctrl-c 5 times
^CYou have pressed ctrl-c 6 times
^CYou have pressed ctrl-c 7 times
^CYou have pressed ctrl-c 8 times
^\[paullik@eucaryota tmp]$