2017-06-29 36 views
0

我想在poll()返回錯誤時在我的代碼中測試場景。但我不知道如何強制poll()返回一個錯誤。我試圖無限制地調用poll()塊並嘗試發送一個SIGINT,但是這只是簡單地停止了這個過程。如何強制poll()出錯

有沒有辦法讓poll()返回一個錯誤?

謝謝。

回答

0

有沒有辦法讓民意調查()返回一個錯誤?

也許有一些錯誤,但存在一些潛在的錯誤。下面是一個通用的方法,不是具體的方法。


有時測試代碼需要用備用代碼注入虛假錯誤。

這種通用方法的正確性是高度依賴的代碼和測試目標。

int poll_result = poll(&fds, nfds, timeout); 
#if TEST1 
    if (poll_result != -1) { 
    // Avoid using rand() 
    static unsigned seed = 0; 
    seed = (16807 * seed) mod 2147483647; // https://stackoverflow.com/a/9492699/2410359 

    if (seed % 97 == 0) { // about 1% of the time 
     // adjust as desired, e.g. EINVAL may not make sense here. 
     int faults[] = { EFAULT, EINTR, EINVAL, ENOMEM }; 
     const unsigned n = sizeof faults/sizeof faults[0]; 
     errno = faults[seed % n]; 
     poll_result = -1; 
    } 
    } 
#endif 
... 

poll() ref見說明部分約EAGAIN, EINTR

當然,使用替代代碼可能會隱藏僅在真實代碼中出現的問題。