2017-04-15 25 views
0

我有一個服務器和客戶端代碼,通過命名管道(FIFO)相互IPC。客戶端向服務器發送SIGNAL(例如SIGUSR1)並檢查是否有給定時間分辨率的任何信號(通過命令行參數)。服務器每次檢查(如果5ms)5ms,檢查5ms後是否有信號到達,如果到達,它會執行一些代碼,如果沒有繼續,直到它捕獲到一個信號。檢查信號是否到達給定的分辨率

所以這就是我的問題所在。我不知道用什麼來做這種動作。我查閱了「Unix系統編程:通信,併發和線程Kay A. Robbins,Steven Robbins」發現了可能用於我的一些函數。睡眠,鬧鐘,uSleep,了nanosleep,暫停。但我不知道在我的情況下使用哪一個。睡眠是沒有問題的,我認爲由於它需要幾秒鐘,我認爲它會在您嘗試轉換爲毫秒時溢出。

一段代碼片段或psudocode會很好理解我。

我只是問如何檢查信號是否以給定的分辨率頻率到達。我必須檢查信號是否以毫秒爲單位。如果信號捕捉,請檢查任何給定的「n」mseconds。

+0

這是不清楚 - 想必你已經註冊的信號處理,但除此之外,我不能告訴你描述。 –

+0

我做了一個信號處理程序。我有2個程序,一個叫做Timeserver,另一個是客戶端。 Timeserver以毫秒爲單位獲取點擊以檢查信號是否到達給定的參數。像「./timeserver 5」會每5毫秒檢查一次信號。如果有信號,信號處理程序當然會運行。我基本上想阻止和解除給定的「毫秒參數」 – opricnik

+0

你不想阻止和解鎖。如果信號到達,您希望信號處理程序設置一個標誌。 – AlexP

回答

0

我認爲函數nanosleep(也可以usleep)可以工作!

  1. 您必須安裝一個信號處理程序循環,可以通過程序被獲取所需的信號,例如:

    #include <signal.h> 
    /* Handler for the signals */ 
    void my_handler(int signum) 
    { 
        if(signum == SIGUSR1) { 
        /* Perform an action on signal SIGUSR1*/ 
        } 
    } 
    int main(int argc, char * argv[]){ 
        /* .... */ 
        /* Install the signal handler to catch the desired signals*/ 
        signal(SIGUSR1, my_handler); 
        /* .... */ 
    } 
    
  2. 你必須等待一個信號。如果發現信號,則必須在處理程序內執行操作,或者使用納秒睡眠中斷時引發的異常。

    #include <time.h> /* Contains nanosleep + timespec definition */ 
    #include <errno.h> /* Contains the errno variable and the ERROR_CODE macros */ 
    #include <stdio.h> /* Contains definition of perror */ 
    #include <stdlib.h> /* Contains the exit function */ 
    
    int main(int argc, char * argv[]){ 
        /* fetch milliseconds from argv and put in a variable named "ms" */ 
        struct timespec interval; 
        interval.tv_sec = 0; /* Seconds*/ 
        interval.tv_nsec = ms*1e6; /* 10^6 Nanoseconds = 1 millisecond */ 
        struct timespec interrupted; 
        /* .. */ 
        while(1) { 
         if(nanosleep(&interval, &interrupted) != 0){ 
          /* The sleeping was interrupted! */ 
          if(errno == EINTR){ 
           //The interruption is due to a signal 
          } 
          else { 
           /*The interruption is due to another cause (read the man page) --> Print an error message */ 
           perror("Nanosleep"); 
           break; /* Exit from main loop */ 
          } 
        } 
        return EXIT_FAILURE; 
        } 
    

另外,您還可以處理的處理程序內部的信號。

替代解決方案 如果您確信的信號都不會來了,並不需要控制每5毫秒,你也可以使用函數pause。事實上該男子頁說:

暫停導致調用進程(或線程)睡眠狀態,直到信號 被傳遞,要麼終止進程或導致 調用一個信號捕獲功能。

在這種情況下,您只需要安裝信號處理程序並等待。

讓我知道它是否回答你的問題。

誠懇你的, 米爾科

+0

謝謝while循環解決方案爲我工作。即使我知道它會%100給我信號我必須使用愚蠢的方式,因爲他們想如何設計。 – opricnik