C++ ifstream from named pipe-如果有数据,请检查非阻塞

C++ ifstream from named pipe-如果有数据,请检查非阻塞,c++,linux,iostream,cin,peek,C++,Linux,Iostream,Cin,Peek,要检查'regular'std::istream,如果有任何挂起的数据,我可以执行如下操作: bool has_pending_data(std::istream& s) { return s.peek() >= 0; } if (has_pending_data(std::cin)) { // process incoming data } else { // do some periodic tasks } 但是,对于标准输入管道和命名管道,这是不同的。如果我这

要检查'regular'
std::istream
,如果有任何挂起的数据,我可以执行如下操作:

bool has_pending_data(std::istream& s) {
  return s.peek() >= 0;
}
if (has_pending_data(std::cin)) {
  // process incoming data
} else {
  // do some periodic tasks
}
但是,对于标准输入管道和命名管道,这是不同的。如果我这样做:

bool has_pending_data(std::istream& s) {
  return s.peek() >= 0;
}
if (has_pending_data(std::cin)) {
  // process incoming data
} else {
  // do some periodic tasks
}

由于执行将阻塞
peek
函数,因此永远不会到达else分支。有没有办法避免对标准输入和命名管道的这种阻塞?

问题是当
std::cin
在I/O缓冲区中没有字符时,
peek
不会返回EOF,而是等待至少写入一个字符

这是因为iostream库不支持非阻塞I/O的概念。我认为C++标准中没有任何东西。

此代码可以帮助您在不阻塞的情况下检查stdin中是否存在数据:

std::cin.seekg(0, std::cin.end);
int length = std::cin.tellg();
if (length < 0) return; //- no chars available

或者,您可以尝试使用该函数。它通常用于网络内容,但如果您将stdin的文件描述符传递给它,它就会工作得很好。

select/poll始终是一个选项,我只是想问是否有办法在香草cpp中不使用linux内容是的,我向您说明了可能的解决方案,使用
seekg
,选择只是最后一次机会。我试着使用你的想法,但似乎没有真正起作用。看来select是我担心发生这种情况的唯一方法,这也是我附加第二个通用解决方案的原因