Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop program for 3 sec in c++ while its running

Tags:

c++

I have no idea of how to stop a program in middle can anyone help me i want my program to stop for a defined sec like 3sec or 6 sec and if you press any key it start running instantly.

like image 263
An kit Avatar asked Oct 15 '22 20:10

An kit


1 Answers

As already stated in the comments section, there is no way to accomplish this in ISO C++. Therefore, you will have to revert to platform-specific functions.

On Microsoft Windows, you can use the function WaitForSingleObject to wait for console input and specify a timeout at the same time. That function will return as soon as there is new input or the timeout has expired. You can check the return value of the function in order to determine which one of these possibilities occurred.

On Linux, you can use select, poll or epoll to accomplish the same thing by waiting on the STDIN_FILENO file descriptor. However, that file descriptor will, by default, only provide new data for reading after the user presses ENTER. Therefore, you may want to disable canonical mode. An alternative may be to use ncurses, but I doubt that this library will be able to provide a file descriptor that is usable in select, poll or epoll. However, I am unfamiliar with ncurses.

EDIT: See the comments section for a very simple solution which uses ncurses.

like image 161
Andreas Wenzel Avatar answered Oct 20 '22 17:10

Andreas Wenzel