【问题标题】:How to force poll() to error如何强制 poll() 出错
【发布时间】:2017-06-29 17:47:38
【问题描述】:

当 poll() 返回错误时,我正在尝试在我的代码中测试一个场景。但我不知道如何强制 poll() 返回错误。我试图让 poll() 无限期地阻塞并尝试向它发送一个 SIGINT 但这只会停止进程。

有没有办法让 poll() 返回错误?

谢谢。

【问题讨论】:

    标签: c sockets network-programming poll-syscall


    【解决方案1】:

    有没有办法让 poll() 返回错误?

    可能存在一些错误,但存在许多潜在错误。下面是一个通用的,不是poll() 特定的方法。


    有时测试代码需要使用替代代码注入虚假错误。

    这种通用方法的正确性高度依赖于代码和测试目标。

    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 的注释部分。

    当然,使用备用代码可能会隐藏只有真正代码才会出现的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-24
      • 2018-04-19
      • 1970-01-01
      • 2016-05-15
      • 2014-12-27
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      相关资源
      最近更新 更多