1

如何捕获程序结束前使用 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.
}
4

1 回答 1

1

我使用了一个名为(来自计数)的全局变量,我在函数ct中递增并显示它。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]$
于 2013-04-14T18:29:01.603 回答