1

How to make user can input commands that won't block application loop. Like it is done in game servers, so admin-user can kick players, or spawn things by issuing console commands.

I have read I can make it by creating new thread for it. But if I will make, let's call it, input thread that will block with std::cin, and then main thread will end, input thread will not join because of std::cin is blocking.

If there is a way of killing such input thread when main thread is about to return - that would be my favorite solution. But I guess there is not such way, or if it exists, it is not to neet or safe.

Also I have read about kbhit implementation based on file descriptor set and select function, but it doesn't work on Windows.

It would be great if the solution wouldn't need me to handle arrow, backspace, delete and shift keycodes by myself.

Mr_KoKa
  • 598
  • 4
  • 13
  • If you have a GUI, there is no `cin`. In a console: If the user enters "stop", just make no more cin after that. – deviantfan Oct 17 '14 at 15:40
  • And yes, kbhit exists on Windows (not required by C or something like that, but it´s there). But i´m not sure if it is kompatible with C++ cin. – deviantfan Oct 17 '14 at 15:41
  • @deviantfan It's console application, if user enters "stop" - yes it quits both threads, but if main thread will end without user input, eg. I need to server close itself if last player left the server, then main thread will return, and input thread will be still blocked. When comes to kbhit, it's a hard way through implementing input from scratch, handling all characters with shift, backspace, delete and arrow keys that will somehow move cursor. cin would be great, only if there is a way to terminate thread which cin is blocking. – Mr_KoKa Oct 17 '14 at 15:47
  • Now I understand. Weeell...someone will cut my head off for this, but clean up all threads except for the closing thread and main, make sure main has no resources which can be explicitely free´d, and terminate the whole program from the closing thread. ... Especially on WIndows, there are some ideas how to do it properly (http://stackoverflow.com/questions/8569027/possible-to-stop-cin-from-waiting-input) but no one is sure if it is really ok to do so. If you have somewhere a leak because of terminating or a leak because you didn´t called the right functions...doesn´t matter. – deviantfan Oct 17 '14 at 16:00
  • @deviantfan - it's fine. The OS is the only entity that can reliably terminate all threads in a process, no matter what state they are in. In general, calling ExitProcess() from ANY thread will take down the whole process 'immedately', no matter whether threads are sleeping, blocked on I/O and/or inter-thread comms, or, (imp... 'most difficult' for user code), running on another core than the one calling ExitProcess. – Martin James Oct 17 '14 at 16:14

0 Answers0