我已经研究这段代码一段时间了,由于某种原因,即使有数据要从 outFds 管道读入, poll 也会返回零。由于某种原因,如果我读入一些数据然后运行轮询,它会返回正确的值,但这不是解决方案。有人以前见过这个并知道我应该做什么吗?
#include <stdio.h>
#include <stdlib.h>
#include <sys/poll.h>
int main(void)
{
int outFds[2];
pipe(outFds);
if(!fork()) {
dup2(outFds[1], 1);
close(outFds[0]);
close(outFds[1]);
// disable printf buffering
setvbuf(stdout, NULL, _IONBF, 0);
sleep(1);
char buf[32];
printf("blah");
exit(0);
}
close(outFds[1]);
char c;
// Read 'b' into c. If this next line is not commented poll returns 1
//read(outFds[0], &c, 1);
struct pollfd outFd;
outFd.fd = outFds[0];
outFd.events = POLLIN;
printf("%d\n", poll(&outFd, 1, 0)); // poll returns 0 for some reason
}
最佳答案
来自联机帮助页:
Specifying a timeout of zero causes poll() to return immediately, even if no file descriptors are ready.
我会将其读取为 timespec 结构,其中 tv_sec
和 tv_nsec
设置为 0
,但似乎将 nullptr
具有相同的效果。
关于c++ - poll返回0但read不阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32644484/