C ++ select()不等待超时时间 [英] C++ select() not waiting for timeout period

查看:506
本文介绍了C ++ select()不等待超时时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用选择功能来接受输入,但是如果用户未输入任何内容,则每2秒执行其他操作.下面的代码在第一次到达select()时等待两秒钟,但是一旦它打印出第一个"timed out"消息,它就会迅速保持打印出来的"timed out",而无需等待2秒,基本上进入了无限循环.有人知道是什么问题吗?感谢您的帮助.

I'm trying to use the select function to accept input but every 2 seconds do something else if the user hasn't entered anything. The code below is waiting two seconds the first time select() is reached but once it prints the first "timed out" message it rapidly keep printing out "timed out" without waiting for 2 seconds, basically entering an infinite loop. Anyone know what the problem is? Thanks for any help.

#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;

const int STDIN = 0;
int main(int argc, int *argv[])
{
struct timeval tv;
fd_set readfds, master;
tv.tv_sec = 2;
tv.tv_usec = 0;
FD_ZERO(&readfds);
FD_ZERO(&master);
FD_SET(STDIN, &readfds);
FD_SET(STDIN, &master);
string buffer = "";
while(buffer != "quit"){
    readfds = master;
    if(select(STDIN+1, &readfds, NULL, NULL, &tv) == -1) perror("select");
    if (FD_ISSET(STDIN, &readfds)){
        getline(cin, buffer);
        cout << "You entered: " << buffer << endl;
    }else
        cout << "Timed out.\n" << endl;
}
return 0;
}

推荐答案

每人:select()可能会更新超时参数以指示还剩多少时间. pselect()不会更改此参数.

per man: select() may update the timeout argument to indicate how much time was left. pselect() does not change this argument.

这意味着如果2秒钟后超时,则可以将tv_sec设置为0.

This implies that if it times out after 2 seconds it could set your tv_sec to 0.

如果timeval的两个字段均为0,它将立即返回.

If both of the fields of timeval are 0 it will return immediately.

尝试在while()内的每个循环中设置超时,以确保不会被覆盖.

Try setting your timeout every loop inside the while() to insure it's not getting overwritten.

这篇关于C ++ select()不等待超时时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆