C语言 如何正确使用 SIGALRM?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16024774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use the SIGALRM correctly?
提问by Luis Quesado
I'm made this code, and I have to use the alarm signal (SIGALRM) to make the program print the message “I am alive.” every 3 seconds.
我制作了这段代码,我必须使用警报信号 ( SIGALRM) 使程序打印消息“我还活着”。每 3 秒。
But it doesn't work, it sends the message "I'm Alive" only when I press CTR-C, I'm guessing I didn't put the SIGALRM function in the right place, can you help me?
但它不起作用,它只有在我按下 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);
}
回答by unautre
Maybe add alarm(3)in your main()?
也许添加alarm(3)您的main()?

