【发布时间】: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
在我使用 rewind 和 fflush 后,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