简体   繁体   English

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

[英]Select always returns 0 in an input file

Select always returns 0 in an input file Select 在输入文件中总是返回 0

I wrote a function function that receives FILE* and checks if it is ready.我写了一个 function function 接收FILE*并检查它是否准备好。

The function: function:

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;
}

I am trying to test this function with check.h .我正在尝试使用 check.h 测试这个check.h

The tests:测试:

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

The result:结果:

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

Select is returning 0 after I use rewind and fflush . Select 在我使用rewindfflush后返回0

When I use read I can retreive the data.当我使用read时,我可以检索数据。

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

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

So select is returning 0 even when I can read data.所以即使我可以读取数据,select 也会返回0

The problem also continues if I try to set a not zero timeout.如果我尝试设置非零超时,问题也会继续。

Why is this happening?为什么会这样?

I need to check if a file is ready to be read.我需要检查文件是否已准备好读取。

What is a possible solution?什么是可能的解决方案?

I can see why you have been led astray, by the 'nfds' parameter to select().我明白为什么您被 select() 的“nfds”参数误导了。 It reads and sounds like "number of file descriptors".它读起来听起来像“文件描述符的数量”。

It is not that.不是那样的。 It should be the value of the highest file descriptor that you care about, plus 1. See (for example) the Linux manpage about it它应该是您关心的最高文件描述符的值加 1。参见(例如) Linux 联机帮助页

As an aside, the nfds parameter is an int - so don't use an unsigned short.另外,nfds 参数是一个 int - 所以不要使用 unsigned short。 It will "just work" generally, but is very confusing.它通常会“正常工作”,但非常混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM