当我在OS X中编译此代码时:
#include <unistd.h>
#include <iostream>
#include <memory>
#include <aio.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
int main(int, char*[])
{
const int iBufSize = 1<<20;
unique_ptr<char[]> pBuffer(new char[iBufSize]);
int iRet;
int iOpts = fcntl(STDIN_FILENO, F_GETFL);
cout << "GETFL Before: " << iOpts << endl;
fcntl(STDIN_FILENO, F_SETFL, iOpts & ~O_NONBLOCK);
iOpts = fcntl(STDIN_FILENO, F_GETFL);
cout << "GETFL After: " << iOpts << endl;
aiocb cb = {0};
cb.aio_fildes = STDIN_FILENO;
cb.aio_buf = pBuffer.get();
cb.aio_nbytes = iBufSize;
iRet = aio_read(&cb);
cout << "aio_read retuned " << iRet << endl;
cout << "errno = " << strerror(errno) << "(" << errno << ")" << endl;
return 0;
}
用g ++编译它,然后执行它:
echo "Hello" | ./aio_read\ demo
它返回:
GETFL Before: 0
GETFL After: 0
aio_read retuned -1
errno = Resource temporarily unavailable(35)
为什么呢?如果我在没有前面的echo "Hello" |
的情况下运行它,它会按预期工作。此外,fcntl调用不是引起问题所必需的,但它们确实显示STDIN没有设置O_NONBLOCK
。