我有一个fd描述符,我可以通过调用来读取它read(fd, buffer,...).现在,我想在实际拨打电话之前检查是否有任何内容需要阅读,因为呼叫是阻塞的.我该怎么做呢?
Jud*_*den 56
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
Run Code Online (Sandbox Code Playgroud)
上面的代码片段将为非阻塞访问配置这样的描述符.如果在调用read时数据不可用,则系统调用将失败,返回值为-1,并且errno设置为EAGAIN.有关更多信息,请参见fnctl手册页.
或者,您可以使用带有可配置超时的select来检查和/或等待指定的时间间隔以获取更多数据.这种方法可能就是你想要的,效率更高.
R..*_*R.. 12
使用select或poll查询文件描述符是否具有可读取的数据:
fd_set fds;
FD_ZERO(&fds);
FD_SET(&fds, fd);
if (select(fd+1, &fds, 0, 0)==1) /* there is data available */
Run Code Online (Sandbox Code Playgroud)
好的,STDIN可以按照您的意愿在非阻塞模式下阅读.您首先需要将套接字设置为非阻塞模式,如
int flags = fcntl(fd, F_GETFL, 0);
if(fcntl(fd, F_SETFL, flags | O_NONBLOCK))
;// some kind of fail
Run Code Online (Sandbox Code Playgroud)
当您准备从缓冲区读取数据时,可以尝试如下读取:
int count;
char buffer[1024];
count = read(fd, buffer, 1024);
if(count < 0 && errno == EAGAIN) {
// If this condition passes, there is no data to be read
}
else if(count >= 0) {
// Otherwise, you're good to go and buffer should contain "count" bytes.
}
else {
// Some other error occurred during read.
}
Run Code Online (Sandbox Code Playgroud)
请注意,缓冲区大小当然1024是任意的.
| 归档时间: |
|
| 查看次数: |
65411 次 |
| 最近记录: |