我制作了这段代码,我必须使用闹钟信号(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);
}
答案 0 :(得分:7)
也许在alarm(3)
中添加main()
?