69415

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

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?

Answer1:

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.

Answer2:

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.

Recommend

  • c# asp .net Convert to MailAddress
  • How does cast in C#/.NET 3.5 work for types with '?' [duplicate]
  • Annoying Flash on UIView Flip Transition
  • Visual Studio warning C4334 on assignment but not on initialization
  • Destructor in virtual inheritance
  • Why List is not a subtype of `List` but is subtype of `List
  • Cannot implicitly convert type 'int' to 'int[]'
  • Is there any way to use an “or” operator in Google Directory API users.list query?
  • Capturing an Objective-C object weakly within C block without declaring an explicit __weak or __bloc
  • list and expandable list in single drawer
  • How to assign System.Drawing.Color to Microsoft.Office.Interop.Excel.ColorFormat
  • How to dynamically declare PARTITION RANGE IN Partition function in sql server
  • VBA suddenly decides it needs declarations
  • Concatenate over dimension in numpy
  • MySQL Connection Closing During Parallel Cron Tasks
  • How to stop insert implicit tags when using `Copy Xpath` in Chrome Developer tools
  • Why isn't mmap closing associated file (getting PermissionError: [WinError 32])?
  • Cocoa Scripting Bridge and element
  • C# WPF check if checkbox is checked error [duplicate]
  • Use variables to set in style with javaScript
  • Can I define `default constructor` in Java?
  • GregorianCalendar constant date
  • Is there a sparse version of tf.multiply?
  • Best way to build a delimited string from a list in java
  • How can I implicitly solve a single equation in Matlab?
  • Avoid `logger=logging.getLogger(__name__)` without loosing way to filter logs
  • Why can I pass a char to a method that takes an int?
  • Are nested classes inside an interface implicitly static and final?
  • Is there ever a reason to implement java.util.Comparable for a type other than itself? [closed]
  • How can I get a file's ctime,atime,mtime and change them using Golang?
  • Having trouble converting string to int
  • Invalid Cast of Type Constrained C# Generic
  • C++11 - emplace_back between 2 vectors doesn't work
  • Get OSVersion in Windows using C++
  • Why does the break statement in ruby behave differently when using Proc.new v. the ampersand sign?
  • Cannot implicitly convert type 'System.Collections.Generic.IEnumerable [duplicate]
  • How to make cin >> not convert float to integer?
  • Will this copy the object or add a reference to it?
  • What if a being-waited thread detaches itself?
  • How can stream manipulators in C++ be functions? [duplicate]
  • Why does a public class/struct in Swift require an explicit public initializer?
  • Why does var infer type object and not XmlNode in XmlNodeList loop?
  • Different ways to assign pointer in C , using & or *?
  • how to pass selectmany combine with groupby to MVC view
  • Converting Float32Array to Uint8Array while Preserving IEEE 754 Representation
  • How can I get the real length of char*? Different between strlen and sizeof(target)/sizeof(target*)?
  • How to install Visual Studio 2017 64bit version explicitly?
  • Making MEF plugins work with Rx
  • Why can the return type of main not be deduced?
  • Does closing a SQLAlchemy ORM Session roll back uncommitted changes?
  • How to serialize a list of lists with the type of custom object?
  • Typescript gives, “Could not find a declaration file for module 'xmlhttprequest'.”
  • Understanding the “Full Result Set” of SSIS
  • Cannot implicitly convert type void to int [closed]
  • How do I expose `UserManager` to my business layer while hiding `IdentityUser`?
  • C# List to ICollection
  • Understanding optional global variables in swift
  • In Scala, why can't I implement a trivial generic function like this?
  • Why is implicit transformation of numerical types inconsistent between “for/comprehension” expressio
  • Javascript: undefined as a function parameter
  • C++. Why I can't compile this code? What is wrong with removing constness using const_cast?
  • implicit conversion
  • Hosting ActiveX control in WPF
  • Ways of returning two dictionaries
  • Why does this generic java method accept two objects of different type?
  • C++11 Lambda functions implicit conversion to bool vs. std::function
  • C#: Cannot convert from ulong to byte
  • Transfer ownership of storage in Splint
  • Casting a string to a generic
  • LINQ query Joins
  • Constructor - order of execution [duplicate]
  • Ambiguous method call when overloading method with generics and lambdas
  • What is a non-trivial destructor in C++?
  • Merging result from 2 columns with same name and not over-writing one
  • Why does comparison of bytes with str fails in Python3
  • Why non-static variable cannot be reference from a static context - reg [duplicate]
  • Could not find implicit value inside singleton object
  • Linq Method Syntax - Can not convert IQueryable to Bool
  • Jersey REST extending methods
  • When is an Object created after a constructor is called
  • What is the difference between inherits and implements in C#
  • What is the equivalent of Solution files in Linux C++ IDE
  • Why is T-SQL ISNULL() truncating the string and COALESCE is not?
  • Do default constructors need to call base class default constructors?
  • How to handle non-ASCII Characters in Java while using PDPageContentStream/PDDocument
  • VBA: Querying Access with Excel. Why so slow?
  • When do superclasses not have a default constructor?
  • Difference between ISymbol.DeclaringSyntaxReferences and ISymbol.Locations
  • How does windowing work in qt embedded?
  • Counting rows in multiple variables using SAS
  • match pattern not working
  • What is the equivalent C# code for a VB.NET anonymous delegate?
  • How to systematically add (decorate) some data to log
  • Google Closure Compiler advanced: remove code blocks at compile time
  • Passing the parameter
  • Auto Login user to website when user is logged in to FB or google - DotNetOpenAuth
  • Swift nested non-optional structure gives optional
  • Tail-Recursive Power Function in Scheme
  • Does mysql_query commit everything
  • How to define a chi2 value function for arbitrary function?
  • Actual SQL statement after bind variables specified
  • Android: Determining number of cameras on 2.2 and above
  • Can I overload the implicit type conversions in Groovy?
  • find in array between dates in mongo
  • REST Url ID Placement for Resources with Collections
  • DB associative entities and indexing
  • C# generic method with one parameter of multiple types
  • About naming the instance variable in Objective C
  • synchronization between processes using unnamed semaphores
  • Clarification on how to use FirstDisplayedScrollingRowIndex
  • Simpler way to deal with Time and Date?
  • Java regex vs XSD regex
  • Common date format function for Oracle-sql and Mysql
  • C++: instantiate a templated class according to an argument
  • getnameinfo specifies socklen_t
  • How to bypass Mechanize “AmbiguityError” in Python
  • Does setting autocommit=0 within a transaction do anything?
  • Ejabberd custom IQ Handler: getting feature-not-implemented or service-unavailable
  • Difference of enum in C and Java
  • How to forbidden wordpress url exchange `&` to `#038;`?
  • Remove Ribbon from Excel
  • Add google places autocomplete to newly generated inputs in list items
  • Visual Studio 2015 has no debug option beyond Remote Machine
  • How to convert a DataGridViewCell to a Control
  • How to print commands in Python?
  • Microsoft.ACE.OLEDB.12.0 Current Recordset does not support updating error received when trying to u
  • How objects are created when the prototype of their constructor isn't an object?
  • Protractor testing in iframe in other non-Angular application?
  • How to get grunt serve task working alongside watch?
  • Connecting Couchbase sync adapter to couchdb server
  • module vs type behavior difference on using F# lambda as actual argument to formal parameter that ex
  • Build entire solution for .NET 4 and .NET 4.5 and copy files to specific folders
  • WP8 + Upload File to Skydrive
  • Pandas multi-index subtract from value based on value in other column
  • Timer once a minute on the minute
  • draw pie chart using iOS quartz 2D
  • detecting connection lost in spark streaming
  • dm-script catch error with “Analyze Particles”
  • How can I have an actor running on one process send a message to another actor running on a separate
  • How to set a thread specific environment variable in Python?
  • CUDA NSight is not installed with CUDA 5.0 installation file on Windows 8? [closed]
  • Netezza Incremental load from Sql server using SSIS
  • How to use SBT with multiple sub project web applications?
  • android-support-v7-appcompat has same attrs as actionbarsherlock library
  • LNK1104: cannot open file 'kernel32.lib'
  • Slicing an SPA into several components and use AngularJS
  • How to create a Unix-domain socket with specific access permissions
  • include dlls in visual studio c++ 2008
  • react split panel resize
  • Can you pass an array from javascript to asp.net mvc controller action without using a form?
  • Enabling DTD support in Sql Server
  • SetWindowsHookEx does not react on media keys
  • Ember.js model to be organised as a tree structure
  • Sequential (transactional) API calls in angular 4 with state management
  • What's the purpose of QString?
  • Create DicomImage from scratch using Dcmtk
  • Installing Apache MyFaces 2 on WildFly 8.2.0
  • Hardware Accelerated Image Scaling in windows using C++
  • How to do unit test for HttpContext.Current.Server.MapPath
  • How to delay loading a property with linq to sql external mapping?
  • Sony Xperia Z Tablet not found by adb
  • How to get a value (ex: baseURL) in every Karate feature?
  • How to convert from System.Drawing.Color to Excel.ColorFormat in C#? Change comment color
  • Validaiting emails with Net.Mail MailAddress
  • Can I make an Android app that runs a web view in Chrome 39?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • How to include full .NET prerequisite for Wix Burn installer
  • Proper folder structure for lots of source files
  • How does Linux kernel interrupt the application?