Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?

喜欢而已 提交于 2019-12-11 01:19:08

问题


When asking the user for input we need to call a blocking function, but I want to be able to "unblock" and resume after a specified timeout has elapsed (usually some seconds).

How can I do this?

std::string s;
// blocking function call
std::cin >> s; // how can I resume operation after timeout duration has elapsed?

回答1:


You cannot do the way you dream, at least not in standard C++11 (using only standardized C++11 functions). You practically need some operating system support, and you implicitly want some event loop (or use some multi-threading approach).

However, you could use your operating system facilities and/or some external libraries.

FWIW, Linux has multiplexing syscalls such as poll(2) (and I am sure that Windows, Android, MacOSX, .... have similar things); but you'll much better use libraries like ncurses or Qt or SFML (see also POCO framework).

Details are considerably more complex than what you imagine, and are operating system specific (but some libraries are frameworks working on several operating systems). See also this & that answers and read the tty demystified page. Be aware that "terminal" is usually today some abstract virtual device, but in the past have been a complex device (which is mostly emulated today).

And don't forget that cin might be something else than a terminal. It might be (on POSIX systems notably) a pipe(7) (command pipeline) or a file (redirection). Then waiting for 5 seconds might be meaningless or useless.




回答2:


You can write a program with main() which creates 2 processes say process1() and process2() using fork() function.

In process1() take Input form user.

In process2() make a delay of X seconds as you say and then terminate the process1 via process2.



来源:https://stackoverflow.com/questions/34108024/timeout-for-blocking-function-call-i-e-how-to-stop-waiting-for-user-input-aft

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!