【问题标题】:Signal Handler for SIGINTSIGINT 的信号处理程序
【发布时间】:2013-12-21 13:18:52
【问题描述】:

我正在编写以下代码。该程序应该能够使用 sigaction 处理 SIGINT。到目前为止,它几乎完成了,但我遇到了两个问题。
第一个问题是如果在 3 秒内收到 3 个信号,程序应该打印“正在关闭”并以状态 1 退出。
第二个问题是我正在使用 gettimeofdaystruct timeval 来获取有关信号到达时间的时间(以秒为单位),但我在这里也失败了。当我尝试它时,我陷入了一个无限循环,甚至以为我在 3 秒内按了 ctrl + C 3 次。此外,由此产生的秒数是相当大的数字。
我希望有人可以帮助我解决这两个问题。这是代码

int timeBegin = 0;

void sig_handler(int signo) {
   (void) signo;
   struct timeval t;
   gettimeofday(&t, NULL);
   int timeEnd = t.tv_sec + t.tv_usec;

   printf("Received Signal\n");

   int result = timeEnd - timeBegin;

   if(check if under 3 seconds) {  // How to deal with these two problems?
       printf("Shutting down\n");
       exit(1);
   }
   timeBegin = timeEnd   // EDIT: setting the time new, each time when a signal arrives. Is that somehow helpful?
}

int main() {
    struct sigaction act;
    act.sa_handler = &sig_handler;
    sigaction(SIGINT, &act, NULL);

    for( ;; ) {
        sleep(1);
    }
    return 0;
}

【问题讨论】:

    标签: c linux signals handler sigint


    【解决方案1】:
    int timeEnd = t.tv_sec + t.tv_usec;
    

    这行不通,因为tv_sectv_usec 是不同的数量级。如果您想要微秒精度,则必须将值存储为更大的类型(例如int64_t)并将秒转换为微秒。

       if(check if under 3 seconds) {  // How to deal with these two problems?
    

    嗯,你试过什么?您有多个信号在不同的时间到达,您需要保留一些关于它们的状态,以了解是否所有信号都在 3 秒内到达。

    【讨论】:

    • 你的意思是像 uint64_t timeEnd = t.tv_sec + t.tv_usecuint64_t timeBegin = 0 ?如何将其转换为微秒,为什么?对于第二个问题,我只是尝试了以下方法: if(result
    • 你必须转换,因为秒和微秒是不同的单位......(你知道“微”是什么意思,对吧?)
    • 好的,我必须使用因子 1000000。但是,如何解决多个信号到达的另一个问题?你能给我至少一些提示吗?
    • 尝试保存有关何时以及有多少信号到达信号处理程序之外的变量的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    相关资源
    最近更新 更多