我希望程序通過鍵入CTRL + C來生成一個SIGINT類型的信號來測試信號的陷阱。我不知道,我只是程序計算的第一中斷信號,並結束程序(只跳直入INTHANDLER功能)如何使Ctrl-c結束程序
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <time.h>
void signalHandler(int signalValue); /* prototype */
void INThandler(int signalValue);
int main(void)
{
int i; /* counter used to loop 100 times */
int x; /* variable to hold random values between 1-50 */
signal(SIGUSR1, signalHandler);
signal(SIGUSR1, INThandler);
srand(time(NULL));
for (i = 1; i <= 100; i++) {
x = 1 + rand() % 50;
if (x == 25) {
raise(SIGUSR1);
}
printf("%4d", i);
if (i % 10 == 0) {
printf("\n");
}
}
return 0;
}
void signalHandler(int signalValue)
{
int response;
printf("%s%d%s\n%s","\nInterrupt signal (", signalValue, ") received.",
"Do you wish to continue (1 = yes or 2 = no)? \n");
scanf("%d", &response);
if (response == 1) {
signal(SIGINT, signalHandler);
}
else {
signal(SIGINT, INThandler);
}
}
void INThandler(int signalValue)
{
signal(signalValue, SIG_IGN);
printf("\nCtrl-C command detected!");
exit(0);
}
首先你設置'signalHandler'處理'SIGUSR1',然後設置'INThandler'來處理它,而不是。你期望發生什麼? – Biffen 2014-12-04 15:27:38