簡體   English   中英

SIGINT的信號處理程序

[英]Signal Handler for SIGINT

我正在研究以下代碼。 該程序應能夠通過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;
}
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秒之內到達。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM