如何在程序结束前捕获SIGINT的使用次数??
例如:在一个只在使用SIGQUIT时结束的程序中,告诉我们用户在结束前按了ctr-c(used 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.
}
最佳答案
我使用了一个名为ct
(from 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]$
关于c - 如何捕获在c中使用SIGINT的次数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16002579/