我编写了这段代码,我必须使用警报信号 ( SIGALRM
) 来让程序打印“我还活着”的消息。每 3 秒。
但它不起作用,它只会在我按下 CTR-C 时发送消息“我还活着”,我猜我没有把 SIGALRM 功能放在正确的位置,你能帮帮我吗?
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
unsigned Count = 0; //Counts the number of times it receives the signal SIGINT.
void mypause(int sign); //prototype of the function my pause.
void mypause(int sign) {
signal(SIGALRM, mypause); //Set alarm clock for 3 seconds.
alarm(3);
printf("I'm Alive");
signal(SIGINT, mypause);
switch (sign) {
case SIGINT:
printf("\nPressed CTR-C\n");
printf("I'm running, waiting for a sign\n");
Count++;
break;
case SIGQUIT:
printf("\nPressed CTR-\\n");
printf("You pressed CTR-C %d times", Conta);
exit(0); //Exit program.
break;
}
}
int main() {
signal(SIGALRM, mypause);
signal(SIGINT, mypause);
signal(SIGQUIT, mypause);
printf("\nI'm running waiting for a signal\n");
while (1) {}
return (0);
}