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関数でインクリメントして表示する (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]$
于 2013-04-14T18:29:01.603 に答える