首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动作捕捉SIGALRM

动作捕捉SIGALRM
EN

Stack Overflow用户
提问于 2014-11-03 21:32:47
回答 1查看 3.5K关注 0票数 2

我的目标是每秒钟发出一个警报,这样当它被sigaction处理时,它就会打印时间,所以每一秒新的时间都会被打印出来。我在这个代码的中间有一个循环,可以计数到一个随机数,但我取出来是为了使这段代码更简洁,更容易查看,因为我相信问题在于我如何使用sigaction,因为它在一秒钟内多次打印,但我只需要这一秒的一行输出。

代码语言:javascript
复制
#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));

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-03 22:00:19

正如其他人所指出的。

您应该将您的sigaction移出循环和警报。

代码语言:javascript
复制
#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()已经包含了一个新行,所以在打印时间时不需要一个行。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26723621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档