我制作了这段代码,我必须使用警报信号( 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);
}

最佳答案

也许在您的 alarm(3) 中添加 main()

关于c - 如何正确使用 SIGALRM?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16024774/

10-11 23:03
查看更多