c - sigaction 捕获 SIGALRM

标签 c

我的目标是制作一个每秒发出一次的警报,以便当它由 sigaction 处理时它会打印时间,因此每秒都会打印新时间。我在这段代码中间有一个循环,它计数一个随机数,但我把它拿出来使这段代码更加简洁并且更易于查看,因为我相信问题在于我如何使用 sigaction,因为它打印了多个一秒钟的时间,但我这一秒钟只需要一行输出。

#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
void alarmPrint(int signum);

time_t curtime;

int main(){

  printf("Enter ^C to end the program:\n");

  struct sigaction sig;

  sig.sa_handler = alarmPrint;

  int count;

  int final;

  time(&curtime);

  srandom(curtime);

  while(1){

    time(&curtime);

    alarm(1);

    printf("\n");

    if(sigaction(SIGALRM, &sig, 0) == -1){

      printf("Error\n");

    }

  }

  return 0;

}


void alarmPrint(int signum){

  printf("current time is %s\n", ctime(&curtime));

}

最佳答案

正如其他人指出的那样。

您应该将 sigaction 移到循环和警报之外。

#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>

void alarmPrint(int signum);

int main(){

  int count;
  int final;

  printf("Enter ^C to end the program:\n");
  signal(SIGALRM, alarmPrint);
  alarm(1);

  while(1) {
    /* do other stuff here */
  }

  return 0;

}

void alarmPrint(int signum){
  time_t curtime;

  time(&curtime);
  printf("current time is %s", ctime(&curtime));
  alarm(1);

}

您还需要在 alarmPrint() 函数中重置闹钟,以便它会在一秒钟内响起。

最后,ctime() 已经包含了一个新行,因此在打印时间时不需要新行。

关于c - sigaction 捕获 SIGALRM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26723621/

相关文章:

c - 循环或多线程哪一个执行时间较长?

c - 从 C 中的另一个文件获取数组

c - 帕斯卡三角形和动态内存分配问题,c

c - 最大子数组代码的段错误

c - 奇怪的十六进制到十进制的转换

c 文件流中的行数

c - 自然对数 - 奇怪的输出

c - 为什么增量运算++a++ 不起作用,至少在 C 中是这样?

我可以将文件描述符共享给 linux 上的另一个进程,还是它们是进程本地的?

c - 无法创建基于基本命令行参数的计算器