【问题标题】:Select always returns 0 in an input fileSelect 在输入文件中总是返回 0
【发布时间】:2022-12-03 10:39:14
【问题描述】:

Select 在输入文件中总是返回 0

我写了一个接收FILE* 并检查它是否准备就绪的功能函数。

功能:

int ioManager_nextReady(FILE *IFILE) {
  // Setting input ifle
  int inDescrp = fileno(IFILE ? IFILE : stdin);

  // Setting timer to 0
  struct timeval timeout;
  timeout.tv_sec = timeout.tv_usec = 0;

  // Variables for select
  unsigned short int nfds = 1;

  fd_set readfds;

  FD_ZERO(&readfds);
  FD_SET(inDescrp, &readfds);

  // Run select
  int nReady = select(nfds, &readfds, NULL, NULL, &timeout);
  if (nReady > 0) {
    return inDescrp;
  }

  return -1;
}

我正在尝试使用 check.h 测试此功能。

测试:

static FILE *tmpIn;

void before(char *line) {
  tmpIn = tmpfile();

  if (line) {
    fprintf(tmpIn, "%s\n", line);
    rewind(tmpIn);
    fflush(tmpIn);
  }
}

void after() { fclose(tmpIn); }

START_TEST(test_ioManager_nextReady_NULL) {
  before(NULL);

  int data;
  data = ioManager_nextReady(tmpIn);

  ck_assert_int_eq(data, -1);

  after();
}
END_TEST

#define LINEIN "Sample input"
START_TEST(test_ioManager_nextReady_text) {
  before(LINEIN);

  int data;

  data = ioManager_nextReady(tmpIn);
  ck_assert_int_ne(data, -1);

  after();
}
END_TEST

结果:

Running suite(s): IOManager
50%: Checks: 2, Failures: 1, Errors: 0
ioManager.test.c:42:F:Smoke:test_ioManager_nextReady_text:0: Assertion 'data != -1' failed: data == -1, -1 == -1

在我使用 rewindfflush 后,Select 返回 0

当我使用read 时,我可以检索数据。

  // Debug
  char bff[MAXLINE];
  int n = read(inDescrp, bff, MAXLINE);
  bff[n] = '\0';

  printf("%d\n", inDescrp);
  printf("%s\n", bff);

所以即使我可以读取数据,select 也会返回 0

如果我尝试设置非零超时,问题也会继续。

为什么会这样?

我需要检查文件是否已准备好读取。

什么是可能的解决方案?

【问题讨论】:

  • 查看 select() 的文档:“nfds 此参数应设置为三组中任何一组中编号最高的文件描述符加 1。”
  • 所以对于单个FD,你应该使用nfsd = inDescrp + 1l

标签: c select fflush rewind


【解决方案1】:

我明白为什么您被 select() 的“nfds”参数误导了。它读起来听起来像“文件描述符的数量”。

不是那样的。它应该是你关心的最高文件描述符的值,加上 1。参见(例如)the Linux manpage about it

另外,nfds 参数是一个 int - 所以不要使用 unsigned short。它通常会“正常工作”,但非常混乱。

【讨论】:

    猜你喜欢
    • 2018-07-06
    • 2011-08-27
    • 2012-12-02
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多